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?