How to make bash scripts executable

Endrit Qerreti

Endrit Qerreti

In this tutorial, you will learn how to make a bash script executable. I published some bash scripts I've been working on lately, and I thought of making a small tutorial how to make these scripts executable, and how to give them the right permission.

Make a bash script executable

To make a bash script executable is easy, however the most important thing is that you need to know what kind of access you are allowing to other users.

To change permissions of a file/folder you can use

u - user - Allows you to change permission for the owner of the file

g - group - Allows you to change permission for a specific group

o - others - Allows to change permissions for all other accounts

To set write,read or execute permission use

x - Allows you to make a file executable, in this case a bash script

r - Allows you to set read permission, for example to make a file readable by only you

w - Allows you to set write permission, you can make a file/folder writeable by you or other users

To add or remove permissions

  • + Allows you to add access
  • - Allows you to remove access

To make a bash script executable, run

chmod +x script.sh

Note: The command above will give access to script.sh to all users, so all users on the same group will be able to execute script.sh

If you want to make this file executable only by you, run

chmod u+x script.sh

To give only read access to the owner of file use

chmod u+r script.sh

For example, create a file script.sh and then run the command above, next try to save something on this file and you should get an error that you don't have permission, because we set only reading permission for the user. We used u-user + r-read permission which removes the ability for write permission.

Make a file executable but not writeable

Let's say you want other users to be able to run your script, but you don't want them to change its content, then use

chmod o+rx,o-w script.sh

o+x gives other users executable permission, then o-w removes the write permission for all other users.

Remove read,write and execute permission for others

chmod o-rwx script.sh

Add read permission but remove write and execute for others

chmod o+r, o-wx script.sh

Give to all users read, write and execute permission

chmod a+rwx script.sh

Give to all users only read permission

chmod a+r, a-wx script.sh

Run the script

Once you give the right permission to the file, execute the script

./script.sh

Conclusion

In this tutorial you learned how to make a bash script executable. And also how to add or remove permission to files