Write a bash script called example3.sh that will print information about the fil
ID: 3873301 • Letter: W
Question
Write a bash script called example3.sh that will print information about the files in the current directory based on the command line arguments (or lack thereof). The syntax is as follows:
example3.sh [file1] [file2] … [fileN]
If no arguments are given, your program will default to all non-hidden files in your current directory. Your program will report the following statistics:
• The number of ordinary, readable, and executable files in your current
directory.
• The number of non-existent (if files specified in command line arguments
do not exist) or “other” types of files in your current directory.
• The number of directories in your current directory.
• The number of ordinary and readable files in your current directory.
• The total number of bytes (size) contained in ordinary and readable files in your current directory.
Please note that no duplication of file counts is allowed (e.g., directories are
counted as directories only, but not executable files even though they are
executable, since they are not ordinary files). Also, only count data from the
current directory and not sub-directories (i.e., files inside directories in the current directories.
Explanation / Answer
#!/bin/bash
print_perm() {
case "$1" in
0) printf "NO PERMISSIONS";;
1) printf "Execute only";;
2) printf "Write only";;
3) printf "Write & execute";;
4) printf "Read only";;
5) printf "Read & execute";;
6) printf "Read & write";;
7) printf "Read & write & execute";;
esac
}
dir="`pwd`/*"
var=0
exec=0
read=0
readexec=0
for entry in $dir
do
if [ -d $entry ]; then
var=$((var + 1))
fi
if [ -e $entry ]; then
perm=$(stat -c%a "$entry")
if [ "${perm:2:1}" = "7" ]; then
exec=$((exec + 1))
fi
if [ "${perm:2:1}" = "4" ]; then
read=$((read + 1))
fi
if [ "${perm:2:1}" = "5" ]; then
readexec=$((readexec + 1))
fi
fi
done
echo "No of directory inside current directory $var"
echo "No of read only file inside current directory $read"
echo "No of read and executable file inside current directory $readexec"
echo "No of executable file inside current directory $exec"
for i in "$@"
do
perm=$(stat -c%a "$i")
FILESIZE=$(stat -c%s "$i")
user=${perm:0:1}
group=${perm:1:1}
global=${perm:2:1}
echo Argument: $i
echo "Size of $i = $FILESIZE bytes."
echo "Permissions :"
printf " Owner Access: $(print_perm $user) "
printf " Group Access: $(print_perm $group) "
printf " Others Access: $(print_perm $global) "
done
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.