3- BASH Scripting – Basic scripting & using variables in script
Hello Linux-fanatics, this is the part 3 of BASH Scripting series. In this tutorial, we will be finally writing our first BASH script & also use variables in our scripts.
As already discussed in Part 1 of the series, first line of a script is “#!/bin/bash” AKA Shebang, which basically tells that the scripts are to run in BASH.
That’s it, just save the file and also provide executing permissions to the scripts,
NOTE We use “#” to write comments in scripts, these comments will not show up in our script’s output.
Modified First Script
Above script was meant to just show how scripts looks like. We can modify to display some more messages
Save & execute. Echo command will print the text in the quotes along with output of the commands.
Using Variables in scripts
In Part 2 tutorial of series, we learned about Environment Variables. Now we can use those in our scripts or we can also define some of our own variables for scripts.
Example We will be using some environment variables like HOME, UID & USER to show user’s information
The script will show current user, their PID & home path.
This script only has environment variables but we can also define some user variables inside our scripts
In scripting while declaring a variable , we can also define output of a command as the variable’s input. This is known as command substitution, & the way we do this is “ user=$(who) ”. You will find yourself using command substitution very much when we go deep into scripting.
Let’s see an example
This is pretty basic example of command substitution.
Here is another example, let’s assume you have to take backup of /home/test/logs file daily & with the below mentioned script
Nice example of how scripting makes life easy.
So this concludes our Part3 of the BASH scripting. We created our first script, used some variables & command substitution in our scripts.
Will be back soon with next tutorial, meanwhile practice as much you can & let me know if you have any queries or suggestions.