Languages
[Edit]
EN

Bash - list files and directories

6 points
Created by:
Root-ssh
121420

In this short article, we would like to show how to list regular files and directories located under indicated path using Bash.

Note: presented solution lets to list visible and hidden files and directories because of .* and * used in the for loop.

print_directory.sh file:

#!/bin/bash

CURRENT_DIR=$(cd "$(dirname "${BASH_SOURCE[0]}")" &> /dev/null && pwd)

cd "$CURRENT_DIR"

for i in .* *
do
	if [ -d "$i" ] || [ -f "$i" ]
	then
		[ "$i" = "." ] && continue
		[ "$i" = ".." ] && continue

		echo "$i"
	fi
done

Example output:

.git
README.txt
documents
pictures
print_directory.sh

Directory structure:

/c/files
    |
    +-- .git/
    +-- documents/
    +-- pictures/
    |    |
    |    +-- pic_1.jpg
    |    +-- pic_2.jpg
    |
    +-- print_directory.sh
    +-- README.txt
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join