Making a Bash script executable involves two main steps:
- Create the script (if you haven't already).
- Change the file's permissions to make it executable.
Step-by-Step Guide to Make a Bash Script Executable
1. Create the Bash Script
If you don't have a script yet, you can create one using any text editor. For example, let's create a simple script called myscript.sh.
Open a terminal and use a text editor to create the script file. Here's an example using nano:
In the editor, write your script. For example:
After writing your script, save the file. In nano, press Ctrl + O to save and Ctrl + X to exit the editor.
2. Make the Script Executable
Now that you have a script file (myscript.sh), you need to change its permissions to make it executable.
Use the chmod command to do this:
chmodis the command to change file permissions.+xadds the "execute" permission for the user, allowing the script to be run as a program.
3. Run the Script
Once you've made the script executable, you can run it.
If the script is in your current directory, use the ./ syntax to run it:
This should output:
Understanding chmod +x
chmod: The command to change file permissions.+x: This part adds the execute (x) permission. Without this, you can’t run the script as a program directly.- Example with
chmod: If you runchmod 755 myscript.sh, it gives full permissions to the owner (read, write, execute), and read and execute permissions to the group and others.
Example Permissions:
You can check the file permissions using ls -l:
Before you run chmod +x:
After running chmod +x:
The key change is the addition of the x in the permissions (rwx for the owner, r-x for group and others).
Notes:
-
Shebang (
#!/bin/bash): It's a good practice to include the shebang (#!/bin/bash) at the top of your script. It tells the system that the script should be executed using the Bash shell, no matter what shell the user is currently in. -
Running Scripts in Other Directories: If your script is located in a different directory (not the current one), you can either specify the full path, or if you want to run it from anywhere, add its directory to the system's
PATH.
