Reputation: 7
I need to make a bash script that checks if the file or directory exists,then if the file does,it checks the executable permission.I need to modify the script to be able to give a file executable permissions from an argument.
Example: Console input ./exist.sh +x file_name
should make the file executable.
This is the unfinished code that checks if the file/directory exists and if the file is executable or not. I need to add the chmod
argument part.
#!/bin/bash
file=$1
if [ -x $file ]; then
echo "The file '$file' exists and it is exxecutable"
else
echo "The file '$file' is not executable (or does not exist)"
fi
if [ -d $file ]; then
echo "There is a directory named '$file'"
else
echo "There is no directory named '$file'"
fi
Upvotes: 0
Views: 891
Reputation: 28326
If you have optional arguments to your script, you need to check for them first.
In the case of just a couple of simple arguments, it would be simpler to check for them explicitly.
MAKEEXECUTABLE=0
while [ "${1:0:1}" = "+" ]; do
case $1 in
"+x")
MAKEEXECUTABLE=1
shift
;;
*)
echo "Unknown option '$1'"
exit
esac
done
file=$1
Then after you have determined that the file is not executable
if [ $MAKEEXECUTABLE -eq 1 ]; then
chmod +x $file
fi
Should you decide to add more complex options, you may want to use something like getops
:example of how to use getopts in bash
Upvotes: 1
Reputation: 37023
Add chmod something like:
if [ ! -x "$file" ]; then
chmod +x $file
fi
This means if file does not have execute persmission, then add execute permission for the user.
Upvotes: 1