Bash: /root/bin/hello_world: Permission denied

bashcentospermissionsshell-script

I am using the CentOS 7.

  1. I wrote my first bash script like this.

    #!/bin/bash
    echo 'this is my first code'
    

    and I saved it as hello_world

  2. I made a directory in my root home directory.

    mkdir bin
    
  3. Then I moved the script to the ~/bin directory.

  4. Then I did this:

    export PATH=~/bin:"$PATH"
    source ~/bin
    
  5. Then I tried to run the script with the below command.

    hello_world 
    

but I did not see the this is my first code but I got a bash: /root/bin/hello_world: Permission denied error instead.

Best Answer

For a script to be executable without executing it with an explicit interpreter (as in bash ~/bin/hello_world), the script file has to have its "executable bit" set. This is done with chmod (see its manual):

chmod u+x ~/bin/hello_world

This sets the executable bit for the owner of the file.

Or,

chmod +x ~/bin/hello_world

This sets the executable bit according to your current umask. Assuming that your umask is 022 (a common default), this will make it executable for all users.


The source step that you did is nonsense and should have given you an error message (you can't source a directory).

If you need the setting of the new PATH to be "permanent", then add the export PATH line to your shell's startup file (~/.bashrc if you're using bash as your interactive shell).


Also, avoid working at an interactive root prompt. Use an unprivileged user account for testing and exploring, and use sudo from that account for those few times that you need to do administrative tasks.

Related Question