How to write a bash script? What steps does it include? And how will we do it? This article will show you an overview of how to write a bash script.
To create and run a shell/bash script, we will do the following 3 steps.
Write an bash script
Table of Contents
Essentially, bash scripts are just a text file. So, to write a bash script file, we need an editor to write it.
On Linux there are many different editors that you can freely use. However, to write scripts smoothly, you should choose an editor that supports syntax highlighting.
The editors support syntax highlighting that allows displaying the color of the lines of code. This will make it easier to see, easily identify the wrong or simply look better.
What is the content of this script file? These are the commands that you type in the Terminal window. Instead of typing each command one by one, you put all the commands into this script file and execute it only once.
Make the script executable
Because as you read above, bash script is actually a text file. On Linux systems there are certain restrictions on permissions. A normal text file will not be considered a program and it cannot be executed.
So, in order to execute the bash script file that you just wrote, you need to assign the executable permissions to it.
At this point, you don’t need to understand what this command really is. You just need to know that you can use it to assign execution permissions to scripts.
danie@linuxmint ~/Desktop $ chmod a+x writebash.com
The above command will grant execution permissions for the script file named writebash.com
.
Put the script somewhere and execute it
Now, put the script in any directory you want on the Linux system. You can move into that directory and execute the script with the following command, for example I am putting the script in the /home/danie/Desktop
folder.
danie@linuxmint ~ $ cd /home/danie/Desktop/
danie@linuxmint ~/Desktop $ ./writebash.com
The important command when executing it is ./writebash.com
with the filename writebash.com
Because the bash script file starts by calling the #! /bin/bash
library, you may not need to move into the directory containing the script and still be able to execute it. With the following command.
danie@linuxmint ~ $ /bin/bash /home/danie/Desktop/writebash.com
The understandable syntax of the above command is (without square brackets): [/bin/bash] [absolute path to file]
So basically you’ve got 3 steps to write a bash script. In the following articles, we will learn more about it.
(This is an article from my old blog that has been inactive for a long time, I don’t want to throw it away so I will keep it and hope it helps someone).