Shell scripts are very useful to run various commands and automate processes in Linux. But when you are starting out, you may find it difficult to run a shell script. In this article, we will look at how to run shell script in Linux. You can use them to execute commands in shell script or run .sh files in Linux. Shell scripts are available in every Linux distribution and they are used by the Kernel itself to handle many of system tasks and processes.
How to Run Shell Script in Linux
Here are the steps to run shell script in Linux.
1. Create Shell Script File
Open terminal and go to the directory (e.g. /home/ubuntu) where you want to create shell script.
$ cd /home/ubuntu
Create an empty shell script file using text editor. Please note, the shell script file must have .sh extension.
$ sudo vi test.sh
Also read : How to Rename Multiple Files in Linux
2. Add Script
Add the following sample script to your file. You can modify it according to your requirements.
#!/bin/bash echo "Hello World"
Please note the first line above. It is used to specify which shell to use for executing your script. We have used the default bash shell which is available in almost all Linux systems. You can also !/bin/sh, !/bin/csh, !/bin/ksh if they are available on your system. It is optional and you can omit but it is generally added as the first line, as a convention, so that Linux knows which interpreter to use.
Save and close the file.
Also read : How to Install Squid Proxy Server
3. Make Shell Script Executable
Before you run the shell script, you need to modify its permissions and make it an executable, with the following command.
$ sudo chmod +x test.sh
Also read : How to Run .bz2 file in Linux
4. Run Shell Script
Finally, run the script using the following command ( ./<filename>)
$ ./test.sh Hello World
Please note the dot and forward slash before the filename. If you want to run the above shell script from a different folder, you need to specify the full path to your shell script.
$ ./home/ubuntu/test.sh
If your system shows “access denied” on running a shell script, or only sudo/root users are allows to run shell scripts then run the above command after sudo keyword.
$ sudo ./home/ubuntu/test.sh
If you want to run the shell script using a specific shell, then run the above file after calling that shell.
$ sudo csh ./home/ubuntu/test.sh
Also read : How to View Hidden Files in Linux
As you can see, it is quite easy to create and execute shell scripts in Linux.
Related posts:
How to Add User to Sudoers in Linux
How to Protect Hard and Symbolic Links in CentOS
How to Check if Directory Exists in Shell Script
How to Split Folder into Subfolders in Linux
How to Remove Unused Kernels in Ubuntu
How to Mount Drive from Terminal
How to Add Newline After Pattern in Vim
What does ${} and $() mean in Shell Script
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.