1

I am trying to create a function in Bash that creates a directory, then sets the ownership, like this:

create_dir() {
  local PATH=$1
  local OWNER=$2
  # create log directory
  echo -e "\n* Creating directory $PATH"
  if [[ -d $PATH ]]  
  then
    echo "  * $PATH already exist, no action done"
  else 
    echo "  * $PATH does not exist, creating dir"
    sudo mkdir $PATH
  fi

  sudo chown $OWNER $PATH
}

then I call it in the same script like this:

# create upload directory, and set owner
create_dir "/www/upload" "deployer"

when I execute the script:

sudo ./dir_setup.sh

it results the following:

* Creating log directory /www/upload * /www/upload already exist, no action done ./dir_setup.sh: line 15: sudo: command not found

Sudo command is installed and works as expected. The same happens with or without using sudo when calling dir_setup.sh If I change the line to

sudo chown $OWNER $PATH

to

/usr/bin/sudo chown $OWNER $PATH

it works fine. I am logged in as user "deployer" I created, has sudoer rights, the owner of dir_setup.sh the same user, has 777 rights.

If I take that line from the function and put it somewhere else, it also works fine. Any idea why do I need to call sudo with /usr/bin/sudo instead of just calling it using sudo when inside a function? And why does it work outside the function?

1
  • Shell variables should be lower-case. Environment variable should be upper-case. (so as to reduce the likely hood of this error). Feb 9 '20 at 22:23
3

You've redefined the reserved variable $PATH, which contains the set of locations in which to search for commands such as sudo.

Don't use all capitals for your variable names, and all will be well.

create_dir() {
  local path="$1"
  local owner="$2"
  # create log directory
  printf "\n* Creating directory %s\n" "$path"
  if [[ -d "$path" ]]  
  then
    printf "  * %s already exists, no action done\n" "$path"
  else 
    printf "  * %s does not exists, creating dir\n" "$path"
    sudo mkdir "$path"
  fi

  sudo chown "$owner" "$path"
}

Notice also that I've double-quoted the variables when they are used, so that their values don't get parsed by the shell.

You could also simplify this at the expense of some logging:

create_dir() {
    local path="$1" owner="$2"

    printf "\n* Creating directory %s\n" "$path"
    sudo mkdir -p "$path"
    sudo chown "$owner" "$path"
}
3
  • OH, thanks, you're completely right!!! I feel so stupid :) But to be honest, i am not a bash expert, as you can see. Thanks for the hints, they are really useful!
    – zak
    Feb 9 '20 at 21:14
  • 1
    @zak Also relevant: Are there naming conventions for variables in shell scripts?
    – Kusalananda
    Feb 9 '20 at 22:46
  • I have renamed all variables to lowercase for safety
    – zak
    Feb 11 '20 at 23:08

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .