Bash Scripting : Get Started !
Contents :
1 ) Basics of Bash scripts : creating your first script
2) Variables in Bash scripts
3) Conditionals in Bash scripts
4) Loops in Bash scripts
5) Taking input in Bash
1 ) Basics Of Bash Scripting : creating your first bash file
What is Bash Scripting ?
Bash (or shell) scripting is a great way to automate repetitive tasks and can save you a ton of time as a developer. Bash scripts execute within a Bash shell interpreter terminal. Any command you can run in your terminal can be run in a Bash script. When you have a command or set of commands that you will be using frequently, consider writing a Bash script to perform it.
Lets Start :
To start with the bash scripting you can use any terminal of your choice , for this tutorial i will be using the Git-Bash.For your better assistance i am adding screenshots as well.
Warming Up :
. There are some conventions to follow to ensure that your computer is able to find and execute your Bash scripts.
. The beginning of your script file should start with #!/bin/bash
on its own line.
. This tells the computer which type of interpreter to use for the script. When saving the script file, it is good practice to place commonly used scripts in the ~/bin/
directory.
Creating a Script File :
Step 1 : Create a Folder
i have created , Bash_Scripts on the Desktop of my computer .
Step 2 : Open terminal inside the folder , or navigate to the folder.
Step 3: Create a Script file , using this command
touch fileName.ext
the ‘touch’ command will create a empty container , of you desired name and file extension
Adding to the Script.sh file :
Add this to the first line of your script file ,
#!/bin/bash
to do that you can use any text editor , i am using VS-Code
now after the first line you can add the commands that you what to display ,
for example :
echo “Put_Your_Name_here”
This will print you name in the terminal ,
but it will be displayed for a glimpse of a second , to resolve this issue
you can use the “sleep” command
sleep .5 # Waits 0.5 second.
sleep 5 # Waits 5 seconds.
sleep 5s # Waits 5 seconds.
sleep 5m # Waits 5 minutes.
sleep 5h # Waits 5 hours.
sleep 5d # Waits 5 days.
sleep command will pause and waits for the time-seed given to it .
To Run/open the created bash file you can use this command ,
./script.sh ## ./ look inside the folder ##
OutPut :
2 ) Variable in Bash Scripts :
What are Variables ?
think of a variable as a temporary store for a simple piece of information. These variables can be very useful for allowing us to manage and control the actions of our Bash Script. We’ll go through a variety of different ways that variables have their data set and ways we can then use them.
Variables are one of those things that are actually quite easy to use but are also quite easy to get yourself into trouble with if you don’t properly understand how they work. As such there is a bit of reading in this section but if you take the time to go through and understand it you will be thankful you did later on when we start dabbling in more complex scripts.
Setting Our Own Variables
As well as variables that are preset by the system, we may also set our own variables. This can be useful for keeping track of results of commands and being able to refer to and process them later.
There are a few ways in which variables may be set (such as part of the execution of a command) but the basic form follows this pattern:
variable=value
This is one of those areas where formatting is important. Note there is no space on either side of the equals ( = ) sign. We also leave off the $ sign from the beginning of the variable name when setting it.
Variable names may be uppercase or lowercase or a mixture of both but Bash is a case sensitive environment so whenever you refer to a variable you must be consistent in your use of uppercase and lowercase letters. You should always make sure variable names are descriptive. This makes their purpose easier for you to remember.
Some Special Variables :
- $0 — The name of the Bash script.
- $1 — $9 — The first 9 arguments to the Bash script. (As mentioned above.)
- $# — How many arguments were passed to the Bash script.
- $@ — All the arguments supplied to the Bash script.
- $? — The exit status of the most recently run process.
- $$ — The process ID of the current script.
- $USER — The username of the user running the script.
- $HOSTNAME — The hostname of the machine the script is running on.
- $SECONDS — The number of seconds since the script was started.
- $RANDOM — Returns a different random number each time is it referred to.
- $LINENO — Returns the current line number in the Bash script.
For in-depth details , and a few tips and trick about variables you can
visit this link : https://ryanstutorials.net/bash-scripting-tutorial/bash-variables.php
3 ) Conditionals in Bash :
Conditionals , allow you to control the execution of commands based upon the internal or external stimuli . that can be a result of some user input or from the pre-defined set of instructions inside the ‘ Bash-Script ’
To start with , conditionals we use the most commonly known conditional
the ( if-else ) statement .
Your First if-else bash-script :
Use if
to start the conditional, followed by the condition in square brackets ([ ]
). then
begins the code that will run if the condition is met. else
begins the code that will run if the condition is not met. Lastly, the conditional is closed with a backwards if
, fi
.
Example Script :
Here is the list of comparison operators for numbers you can use within bash scripts:
- Equal:
-eq
- Not equal:
-ne
- Less than or equal:
-le
- Less than:
-lt
- Greater than or equal:
-ge
- Greater than:
-gt
- Is null:
-z
To compare two string values , ‘ == ‘ equality operator is used and to check the in-equality we use ‘ != ’ . Take an example of two strings that are pre-defined in a bash-script…
string1 = “alpha”string2 = "beta"if [ $string1 == $string2 ]
then
echo "Strings are equal"
else
echo "Strings are not equal"
fi
4) Loops In Bash :
for , while and Until … three loops to rule em all
loops in scripts or in any programming language , keeps on executing smae set of instructions until the code hits a break point , this break point can be anything from a simple return value to a certain number of times a loop is executed/called.
For _ Loops :
A for loop is used to iterate through a list and execute an action at each step. For example, if we had a list of words stored in a variable paragraph
, we could use the following syntax to print each one:
for word in $paragraph
do
echo $word
done
Note that word
is being “defined” at the top of the for loop so there is no $
prepended. Remember that we prepend the $
when accessing the value of the variable. So, when accessing the variable within the do
block, we use $word
as usual.
While_loops :
while loops , deploys the code at-least one time , before updating the decision variable . There syntax is keyword ‘ while ’ followed by set of square-brackets
[ ] with the conditions inside them , at last the loop is closed by using ‘done’ keyword
while [ condition ]
do
// instructions
done
Note that arithmetic in bash scripting uses the $((...))
syntax and within the brackets the variable name is not prepended with a $
.
5) Taking input in Bash :
To take inputs in the terminal we simply use the ‘read’ command followed by the variable name , to call the variable the name of variable is prepended by ‘$’.
#!/bin/bash
read var_name
echo $var_name
More with Read
You are able to alter the behaviour of read with a variety of command line options. (See the man page for read to see all of them.) Two commonly used options however are -p which allows you to specify a prompt and -s which makes the input silent. This can make it easy to ask for a username and password combination like the example below:
#!/bin/bash
# Ask the user for login details\read -p ‘Username: ‘ uservar
read -sp ‘Password: ‘ passvar
echo
echo Thankyou $uservar we now have your login details
______________________________THE END__________________________
This , read is just a basic introduction to the world of bash scripting and how you can automate tasks and increase your productivity.
For projects related to , bash_scripts follow the GitHub repo linked below :