4

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.

  • Have you given your script execute permissions with chmod u+x? – dsstorefile1 May 22 '18 at 5:25
  • oh no, i forgot to grant the proper right to this file. thank you Muru – Dean Zhang May 22 '18 at 5:29
  • 1
    Note also, that source ~/bin doesn't make sense. From the context, we see that bin must be a directory, and you can't source a directory. – user1934428 May 22 '18 at 6:39
  • 2
    +1 for extually including all relevant information in the question and not just saying "It doesn't work" like many others do. – Kusalananda May 22 '18 at 7:01
5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.