0

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
5
  • It just checks if the file is executable. I need it to be able to change the permission. Commented Jan 2, 2015 at 15:07
  • 1
    Do you know how to change permissions of a file? Commented Jan 2, 2015 at 15:08
  • 1
    So add a chmod command, what's the problem? Commented Jan 2, 2015 at 15:08
  • Yo do know about the chmod command? Commented Jan 2, 2015 at 15:08
  • Yes I know to use chmod +x file_name but I don't know how to implement it in the script :( Commented Jan 2, 2015 at 15:09

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Or just use $1 as the argument to chmod directly if it is the change you want to make to the file and you've asserted that it is a safe/correct mode already.
1

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.

3 Comments

Yes I know. But I am supposed to give the chmod permission from the terminal when executing the script. Ex: ./exist.sh +x file_name
Or viceversa ./exist.sh -x file_name
Then try: chmod +x file_name; ./exist.sh .. by writing -x after ./exist.sh you are trying to pass parameter to shell script and its not going to change the permission of your script.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.