Search code examples
linuxbashloopsls

Using ls command result in a loop


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


Solution

  • 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.