-3

I want to use the result of ls command in a loop to check if for example the first line is a directory, second etc. For example I have this folder that contains one directory the script should display:

18_05_2018 is directory

enter image description here

Robin Green
  • 32,079
  • 16
  • 104
  • 187

1 Answers1

0

Create a file named is_file_or_directory.sh containing:

cd "$1" || echo "Please specify a path" && exit
for i in *; do
    if [[ -d $i ]]; then
        echo "$i is a directory"
    elif [[ -f $i ]]; then
        echo "$i is a file"
    else
        echo "$i is not valid"
        exit 1
    fi
done

Make that file executable with:

sudo chmod +x is_file_or_directory.sh

Run the script specifying as a parameter the path that you want to analyze:

./is_file_or_directory.sh /root/scripts/

Output:

jeeves ~/scripts/stack # ./is_file_or_dir.sh /root/scripts/
databe.py is a file
is_file_or_dir.sh is a file
mysql_flask.py is a file
test is a directory

Here's a more detailed explanation of what is happening under the hood. The variable $1 is, in Bash, the first parameter sent to the script. In our case it is the path where the script will perform its actions. Then we use the variable $i in the loop.

$i content will be every file / folder name in the path $1. With -d and -f we check if $i is a file or a folder.

halfer
  • 19,824
  • 17
  • 99
  • 186
Pitto
  • 8,229
  • 3
  • 42
  • 51
  • 1
    `for file in $(ls)` is [BashPitfalls #1](http://mywiki.wooledge.org/BashPitfalls#for_i_in_.24.28ls_.2A.mp3.29), and the subject of [Why you shouldn't parse the output of `ls`](http://mywiki.wooledge.org/ParsingLs). It's not a practice we should be teaching. Moreover, `ls $1` is missing quotes, so if the script were run as `./run-script-with "My Documents"`, it would first look for a directory `My`, then a second directory `Documents`. – Charles Duffy May 19 '18 at 20:31
  • Thanks for the suggestion, @CharlesDuffy, I am now correcting my code – Pitto May 19 '18 at 20:39
  • thank you very mutch @Pitto and sorry for being late I had some exams – Yusuf Mu'min May 21 '18 at 20:53
  • @Pitto, ...consider `cd "$1" || exit` -- without the quotes, `cd` into directory names without quotes will fail; without the `|| exit`, the code will continue to run in the wrong directory if the `cd` fails. – Charles Duffy May 21 '18 at 21:12
  • Nice addition, @CharlesDuffy! I also took the freedom to inform the user about what happened. Thanks for the suggestions :) – Pitto May 22 '18 at 09:49