How Do I Execute a Bash Script in Terminal
Bash scripts can be written using any text editor, and the file must have the “.sh” extension. Bash scripts are often used to simplify repetitive tasks or to automate processes that would otherwise require a series of manual commands to be executed in the terminal. Bash scripts can be run in a variety of ways, including running them directly in the terminal, scheduling them to run at specific times using cron jobs, or including them as part of a larger program or script, here are the four ways to run a bash script in terminal:
- Running a Bash Script Using Source Command
- Running a Bash Script by Specifying Path
- Running a Bash Script Using the Bash Interpreter
- Running a Bash Script Using sh Command
1: How to Run a Bash Script Using source Command
If you want to execute a bash script in the current shell session rather than in a new process, you can use the source command and here it its syntax:
Now to illustrate how to run the shell script using the above syntax I have executed a script:
2: How to Run a Bash Script by Specifying Path
The most straightforward way to execute a bash script is to run it by specifying its path. If in case the script that is to be executed is in the placed in the current directory then use the following syntax:
It may happen that you might not be able to run the bash file this way due to restricted permissions so in that case use the below syntax to change the permissions of the respective bash file:
If the script is in a different directory, you can specify the path to the script:
Now if you are in the same directory as that of bash file directory then follow the given syntax:
Now to further illustrate to clarify how to use this above given syntax I have executed a bash script like this:
3: How to Run a Bash Script Using the Bash Interpreter
Another way to execute a bash script is by executing it through the bash interpreter and you can do this by calling the bash interpreter and passing the path to the script as an argument, here is the syntax in this regard:
Now to illustrate how to run the shell script using the above syntax I have executed a script:
This method is useful if you want to ensure that the script is executed using bash, even if it has a different shebang line.
4: How to Run a Bash Script Using the sh command
If your script does not contain any bash-specific features and can be executed by any POSIX-compliant shell, you can run it using sh, here is the syntax for it:
Now to illustrate how to run the shell script using the above syntax I have executed a script:
Conclusion
Bash scripts can be used to manipulate files, perform text processing, and automate administrative tasks. The flexibility and versatility of bash scripts make them a powerful tool for system administrators, developers, and power users. There are several ways to execute a bash script in the terminal, and the best method to use depends on your specific requirements.