Home Linux Shell Script that checks if every argument supplied is a file or directory

Shell Script that checks if every argument supplied is a file or directory

by Anup Maurya
1 minutes read

In this article, we’ll learn to write a Shell Script that checks if every argument supplied is a file or directory.

Shell script that receives any number of file names as arguments, checks if every argument supplied is a file or directory, and reports accordingly. If the argument is a file, it reports the number of lines present in it using the wc -l command

#!/bin/bash

# Loop through all arguments
for arg in "$@"
do
    # Check if the argument is a file
    if [ -f "$arg" ]
    then
        echo "$arg is a file and has $(wc -l < "$arg") lines"
    # Check if the argument is a directory
    elif [ -d "$arg" ]
    then
        echo "$arg is a directory"
    # If the argument is neither a file nor a directory, report an error
    else
        echo "$arg is not a file or directory"
    fi
done

Save the above script to a file (e.g., report-files.sh), make it executable using the chmod +x report-files.sh command, and then run it with the file names you want to check as arguments. For example, if you want to check the files file1.txt, file2.txt, and the directory mydir, you can run the script as follows

./report-files.sh file1.txt file2.txt mydir

The script will output something like this

file1.txt is a file and has 10 lines
file2.txt is a file and has 20 lines
mydir is a directory

related posts

Leave a Comment

Enable Notifications OK No thanks