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:
#!/bin/bash
# Check if at least one file path has been provided
if [ $# -lt 1 ]
then
echo "Usage: $0 file..."
exit 1
fi
# Loop over all file paths
for FILEPATH in "$@"
do
if [ -e "$FILEPATH" ]
then
echo "File: $FILEPATH"
echo "Type: $(file -b "$FILEPATH")"
echo "Size: $(du -sh "$FILEPATH" | cut -f1)"
echo "Last modified: $(date -r "$FILEPATH")"
else
echo "File: $FILEPATH does not exist."
fi
echo
done
Here’s a step by step explanation:
- 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.
- The for loop iterates over each file path provided as an argument.
- 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.
- 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.
- 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.
- The date -r “$FILEPATH” command is used to print the time of the last modification of the file.
- The loop then continues to the next file path, until all file paths have been processed.
Other urls to refer