Shell : Checks whether each file exists or not by giving list of paths.

Shell Scripting @

In this article we will discuss a script that takes a list of file paths as input and checks whether each file exists or not. If the file exists, it will tell us the file type, size, and the time of the last modification.

Shell script:


# Check if at least one file path has been provided
if [ $# -lt 1 ]
    echo "Usage: $0 file..."
    exit 1

# Loop over all file paths
for FILEPATH in "$@"
    if [ -e "$FILEPATH" ]
        echo "File: $FILEPATH"
        echo "Type: $(file -b "$FILEPATH")"
        echo "Size: $(du -sh "$FILEPATH" | cut -f1)"
        echo "Last modified: $(date -r "$FILEPATH")"
        echo "File: $FILEPATH does not exist."

Here’s a step by step explanation:

  1. The script expects one or more file paths to be provided as command-line arguments. If no argument is provided, it outputs a usage message and exits.
  2. The for loop iterates over each file path provided as an argument.
  3. The if condition checks if the file exists using the -e option. If the file exists, it executes the following commands, otherwise it outputs a message stating that the file does not exist.
  4. The file -b “$FILEPATH” command is used to determine the type of the file. The -b option tells file to omit the filename in its output, so it just prints the file type.
  5. The du -sh “$FILEPATH” | cut -f1 command is used to find the size of the file. du -sh estimates file space usage, and cut -f1 extracts the first field from its output, which is the size of the file.
  6. The date -r “$FILEPATH” command is used to print the time of the last modification of the file.
  7. The loop then continues to the next file path, until all file paths have been processed.

Other urls to refer

Author: user

Leave a Reply