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
fedorqui
  • 275,237
  • 103
  • 548
  • 598
Selendi
  • 7
  • 6

2 Answers2

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.

SMA
  • 36,381
  • 8
  • 49
  • 73
  • 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 – Selendi Jan 02 '15 at 15:13
  • Or viceversa ./exist.sh -x file_name – Selendi Jan 02 '15 at 15:13
  • 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. – SMA Jan 02 '15 at 15:16
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

Community
  • 1
  • 1
Joe
  • 25,000
  • 3
  • 22
  • 44
  • 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. – Etan Reisner Jan 02 '15 at 16:37