Name: ID: Q1) In shell scripting, it is possible to test if a file exists using
ID: 3184696 • Letter: N
Question
Name: ID: Q1) In shell scripting, it is possible to test if a file exists using the e" option. For example, if the file name is $F then a test such as if [-e “$F” ] is true if file exist. It is required to write a shell script that asks the logged user to enter a filename name. If there is no such filename, the script should display a message saying that and terminate. If filename exist, do the following: If the file is a C program, compile the file and execute it on successful compilation. If the file type is shell script, display its last date modified and all of its printing statements. If the file type is directory, display the number of items in that directory and its recursive contents view showing the type of each listed item. For other file type, deny both group and others from accessing the file and give the user the choice to delete it. termExplanation / Answer
solution:
# function to recursively iterate through a folder
folder_recurse() {
for i in "$1"/*;do
if [ -d "$i" ];then
echo "dir: $i"
folder_recurse "$i"
elif [ -f "$i" ]; then
FILETYPE=`file $F1 | cut -d -f2`
echo "file: $i $FILETYPE"
if [ $FILETYPE == "Other" ]
then
echo "Do you want to remove $i(y/n)"
read CHOICE
if [ $CHOICE == "y" ]
then
rm $i
fi
fi
fi
done
}
echo "Please enter a filename:"
read F1
# Does the file exist
if [ ! -e $F1 ]
then
echo "Not exists"
fi
#Is the file executable
if [[ -x $F1 ]]
then
chmod u+x $F1
./$F1
fi
# Get file type
TYPE=`file $F1 | cut -d -f2`
if [ $TYPE == "ASCII" ]
then
chmod u-w $F1
chmod g-w $F1
cat $F1
fi
# Is it a directory
if [ -d $F1 ]
then
chmod +rx $F1
folder_recurse $F1
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.