Search code examples
bashchmodpermission-denied

Bash: `chmod a+x` Not Working When Run Inside Script


I'm trying to simulate an update process via script.

I only care about the update script's exit code (0 for success and any other value for failure).

I have created a simple script called update.sh to simulate an update:

#!/bin/bash

# 1=true, 0=false
success=1

if [ $success -eq 1 ] ; then
    # Success.
    exit 0
else
    # Failure.
    exit 1
fi

To simulate a downloaded update, I have zipped update.sh into a file called update-file.zip.

My main script extracts update-file.zip and runs update.sh:

#!/bin/bash

# Create a fresh update folder.
rm -rfv /test/update && mkdir /test/update

# Simulate download by copying zip file to that folder.
cp -rf /update-file.zip /test/update/

cd /test/update
unzip -o update-file.zip

# Make the update script executable.
updateFile="/test/update/update.sh"
chmod a+x $updateFile

# Run the update.
/test/update/update.sh

if [ $? -ne 0 ] ; then
    echo "update failed"
else
    echo "update success"
fi

# Delete update folder.
rm -rfv /test/update

However, when I run my main script (even with sudo), I get the following error message:

/test/update/update.sh: Permission denied

Not even using a service (that uses root to do everything) helped, as I still got the same error message.

It seems that chmod a+x is not working when run inside scripts, because if I run chmod a+x /test/update/update.sh on the terminal, everything works fine.

Whenever chmod a+x is run from a script, I get "Permission denied" errors when trying to run the affected script.

What puzzles me is that when I run ls -l /test/update/update.sh, I get the following:

-rwxrwxrwx 1 root root 131 Sep  9  2020 /test/update/update.sh

The output is the same regardless of whether chmod a+x is run from the terminal or a script.

I am on Ubuntu Server 20.04.1 LTS (Focal Fossa).


Solution

  • You may explicitly run the interpreter for the file:

    bash /test/update/update.sh
    

    There is no need to make the file executable then.