From this text I’m going to introduce you “The Bash Script“.
WHAT IS BASH SCRIPT?
Bash Script is a text file with the extension of ‘.sh‘. How ever as LINUX is a extension less Operating System it doesn’t matter. From a bash script, we say to the computer what to do. All the commands what we used in the terminal, can use in bash script as well. Any command you type on the terminal can be used with the bash script in the same way. The out put will be the same.
Let’s take an example,
- I’m going to create a basic bash command which will print a line on the terminal. First of all I’m going to create a file.
- Then type these commands in the text editor.
There are some special things here. ‘#‘ is used to put comments. Any comment will not execute in the terminal. ‘#!‘ is known as the “shebang” . Then ‘/bin/bash‘ is the interpreter of our bash shell. It is used to execute the file. The third line is what we want to print.
- Next we have to change permission of the file.
chmod o+x myScript
- Next we can execute the bash script by giving super user permission to the command.
- It will print the ‘hSenid Mobile’ on the terminal.
From the next example let’s see how to use variables.
- The same example but this time I have used a variable to store the name ‘hSenid Mobile’.
Something to remember here is, there is no space between the variable_name and the variable_value.
Using variables will help us to reuse the same value multiple times.
Also there is a scope for the variables in the bash script. There are two types of variables,
- Global Variables : can access anywhere on the script
- Local Variables : only for a specific function.
Let’s see how to use them in separate.
- I’m creating a Global variable and a Local variable,
From the above example you can see that Global variables can accessed anywhere within the code and local variables are only accessible within the same function where it is declared.
Also we can take inputs from the user through the terminal to used within the code too. This is much more interesting than the rest.
- I’m creating a new file.
- Next type this code in your file.
‘read‘ command is used to read the input through the terminal. Then we can use those values later by storing on variables.
- Now let’s see what happen next…
See we can use the user entered values in the terminal too.
Not only the variables. We can use arrays in bash script too.
There are so many uses in bash script. Arithmetic manipulation is also possible with the bash script as well.
Something to remember here is, with the ‘let‘ command we have to write everything without any spaces. Also we can store the output value to a variable using let command. On the other hand ‘let’ command can be used with “”, then we can keep the spaces within the numbers.
I hope you got an idea about what is bash scripting and how to use them in practically. Hope to see you soon with another interesting topic. Thank You!