A shell in Unix or Linux is a command-line interpreter that serves as an interface between a user and kernel. Mainly, it is used to execute programs or commands. Hence, a shell script is essential for efficiently executing multiple Linux commands.
However, many beginners don’t know how to create shell scripts and sometimes get errors. So in this tutorial, we will explain different ways to create a shell script in Linux.
How to Create a Shell Script in Linux?
Let’s divide this section into multiple sections to explain various methods to write shell scripts quickly.
Method 1 – Using a Default Text Editor
You can use any text editor to write a shell script, so let’s use Ubuntu’s default text editor to create an example.sh script.
First, open the directory in the terminal in which you want to create a shell script and then execute the following commands:
touch example.sh
chmod +x example.sh
The chmod command makes the file executable by giving it executable privileges. Always remember that the extension of the file or folder in which your shell script is being written is ‘.sh.’
Please use the below command to open a shell script in the nano editor:
nano example.sh
You can now edit the script and enter any specific information accordingly. Once you are done, press the Y button on your keyboard to finalize the changes in the script.
You can open the shell script through any text editor, whether GUI-Based or CLI.
Method 2 – Using Vim Editor
Almost every Linux distro has the vim editor pre-installed in the system. You can install it with the command given below:
sudo apt install vim
Next, type the name of the shell script in the following command and then execute it:
vi <filename.sh>
Add the information you want to add to the script and then save it to make changes. In case you want to check the shell script data, please run one of the following commands:
bash example.sh
OR
./example.sh
Method 3 – Add Commands in a Shell Script
In a shell script, if you want to enter a command, please use # before the specific line. Let’s understand it through an example in which we will add commands in the ‘example.sh’ script.
Once you execute the above script, the terminal will print the command’s output instead of the commands as shown below:
Wrapping Up
We hope that you can now create your shell script in Linux without any issues. You can use any text editor program on Linux and open a new file to do shell programming or write a script.
We recommend you use the touch command as it gives a simple way to create and write shell scripts quickly.
Aditya is a seasoned JavaScript developer with extensive experience in MEAN stack development. He also has solid knowledge of various programming tools and technologies, including .NET and Java. His hobbies include reading comics, playing games, and camping.