We\'ve seen operations [ - e object] to test if something exists. More specific
ID: 3817096 • Letter: W
Question
We've seen operations [ - e object] to test if something exists. More specific operations such as [ - f object] or [ - d object] will test if it exists and is a file or a directory, respectively. There are a few more like that: - r, - w, and - x will check whether the file has the permissions r, w, or x for example. The - O will check if it's owned by the current user. Write a script that takes a file as argument. If the file doesn’t exist, it says so to the user. If the file exists, it displays what permissions are currently turned on for this file, and tells the user whether he/she can change them
Explanation / Answer
echo -n "Enter the file name :"
read file #Reading file name.
if [ -e $file ] #Checking if the file exists or not. '-e' checks for existence.
then
echo "The present permissions are :"
#First long listing out the details.
#And then passing them as input into cut command using pipeline.
#cutting the first 10 characters of the 'ls -l' command output using '-c' option.
ls -l $file|cut -c 1-10
#Introducing two variables for current user and file owner.
user=""
owner=""
#Checking the owner of the file from 'ls -l' output's third column.
owner=`ls -l $file|cut -d ' ' -f 3`
echo "Owner of the file $file = $owner"
#Checking the current user in the host.
user=`whoami`
echo "User of the file $file = $user"
#Checking if user and owner of the file is same or not.
if [ "$user" == "$owner" ]
then
echo "As the user and the owner of the file $file is same."
echo "So you have permissions to change file permissions."
#If user is not the owner of the file.
else
echo "As the user and the owner of the file $file is not same."
echo "You don't have permissions to change file permissions."
fi
#If file does not exists.
else
echo "$file not found."
fi
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.