SCRIPT 1 ASSIGNMENT Write a script faddexec.sh that takes a filename as an argum
ID: 3838488 • Letter: S
Question
SCRIPT 1 ASSIGNMENT Write a script faddexec.sh that takes a filename as an argument and adds execution permission to the file for the user if the file is a regular file. Make sure that your script checks for error conditions. Use the following pseudocode to develop your script:
#!/bin/bash if # of
arguments is one then
if file in $1 exists
then
if file in $1 is a regular file
then
add execute permission
else
print message that this is not a regular file
fi else
print message that the file does not exist
fi else
print the "Usage" message
fi
Explanation / Answer
Code:
#!/bin/bash
##########################################################################################
# Script to add execution permission to the file for the user if the file is a regular file
##########################################################################################
# Checking if user has passed the filename as an argument
if [ $# -ne 1 ]
then
echo "Must pass filename as an argument. Usage: $0 <filename>"
exit
fi
# Assiging the file passed in commandline to variable filename
filename=$1
# Checking if filename exists
if [ -e $filename ]
then
# checking if file is a regular file
if [ -f $filename ]
then
# adding execute permission to the regular file
chmod +x $filename
echo "File $filename has execute permission added"
else
# printing message not regular file as file is not a regular file
echo "File $filename is not a regular file"
fi
else
# printing message when filename does not exist
echo "File $filename does not exist"
echo "Usage: $0 <filename>"
fi
NOTE: Give execute permission (chmod +x faddexec.sh) to the file "faddexec.sh" once you saved the code in your system
Execution and output:
186590cb0725:Shell bonkv$ ./faddexec.sh
Must pass filename as an argument. Usage: ./faddexec.sh <filename>
186590cb0725:Shell bonkv$ ./faddexec.sh 1
File 1 does not exist
Usage: ./faddexec.sh <filename>
186590cb0725:Shell bonkv$ ./faddexec.sh 2
File 2 does not exist
Usage: ./faddexec.sh <filename>
186590cb0725:Shell bonkv$ ./faddexec.sh 1 2
Must pass filename as an argument. Usage: ./faddexec.sh <filename>
186590cb0725:Shell bonkv$ ls -ld test
drwxr-xr-x 2 bonkv 1896053708 68 May 12 13:27 test
186590cb0725:Shell bonkv$ ./faddexec.sh test
File test is not a regular file
186590cb0725:Shell bonkv$ ls -tlrh groups
-rw-r--r-- 1 bonkv 1896053708 125B Apr 29 07:51 groups
186590cb0725:Shell bonkv$ ./faddexec.sh groups
File groups has execute permission added
186590cb0725:Shell bonkv$ ls -tlrh groups
-rwxr-xr-x 1 bonkv 1896053708 125B Apr 29 07:51 groups
186590cb0725:Shell bonkv$
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.