Dec 13, 2014 05:35 PM
(This post was last modified: Dec 16, 2014 04:57 PM by Tirus.)
Comprehensive bash guide
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
What is bash?
Bash (Bourne Again Shell) is a unix shell written by Brian Fox for the GNU project to replace sh (Bourne Shell).
It is a command processor that typically runs in a text window, where the user types commands that cause actions. Bash can also read commands from a file, called a script. Like all Unix shells, it supports filename wildcarding, piping, here documents, command substitution, variables and control structures for condition-testing and iteration
Your first script
Let's start with something that is really easy to understand. Lets create a "hello world" script.
PHP Code
<?php
#!/bin/bash
echo "Hello World"
- This line tells the application which application to run the script with. In our case it is Bash.
- 'echo' is used to print something out on the terminal. In our case the echo will print "Hello World" out without the quotes.
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
Running a bash script
So after creating your first ever bash script, let's say you saved the contents of the bash script with the name "firstever.sh". The script should have execute permissions for the correct owners in order to be runnable. When setting permissions, check that you really obtained the permissions that you want. When this is done, the script can run like any other command.
PHP Code
<?php
chmod u+x firstever.sh
Now that we have gaven our script the permission to run like any other command, we can execute our first bash script! To do this, we will simply type firstever.sh in our terminal. It should look something like this
PHP Code
<?php
firstever.sh
"Hello World"
This is the most common way to execute a script. It is preferred to execute the script like this in a subshell. The variables, functions and aliases created in this subshell are only known to the particular bash session of that subshell. When that shell exits and the parent regains control, everything is cleaned up and all changes to the state of the shell made by the script, are forgotten.
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
Variables
You can use variables as in any programming languages. There are no data types. A variable in bash can contain a number, a character, a string of characters. You have no need to declare a variable, just assigning a value to its reference will create it.
PHP Code
<?php
#!/bin/bash
BH="Hello World!"
echo $BH
Line 2 creates a variable called BH and assigns the string "Hello World!" to it. Then the VALUE of this variable is retrieved by putting the '$' in at the beginning. Please notice (try it!) that if you don't use the '$' sign, the output of the program will be different, and probably not what you want it to be.
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
Local Variables
Local variables can be created by using the keyword local.
PHP Code
<?php
#!/bin/bash
HELLO=Hello
function hello {
local HELLO=World
echo $HELLO
}
echo $HELLO
hello
echo $HELLO
This script here assigns the word "Hello" to "HELLO". We then make a function named "hello" which HELLO = World. Once we echo "$HELLO" it will echo out the variable we made it to, which is world in this case. Now, whenever we execute it again, it'll go back to the first part and execute "Hello" which would print out "Hello world". Fairly basic, right?! Great!
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
Conditionals
Conditionals let you decide whether to perform an action or not, this decision is taken by evaluating an expression. This is useful for if statements, then statements, elseif statements and multiple other statements. You will use conditionals very often in your bash lifetime so get use to them. I will be going over a few conditionals in this section of the guide.
If
PHP Code
<?php
#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
fi
Programming conditional statement that, if proved true, performs a function or displays information. Below is a general example of an if statement, not specific to any particular programming language. The code to be executed if the expression within braces is true can be found after the 'then' word and before 'fi' which indicates the end of the conditionally executed code.
If then else
PHP Code
<?php
#!/bin/bash
if [ "foo" = "foo" ]; then
echo expression evaluated as true
else
echo expression evaluated as false
fi
So this little script here says that if the variable foo is equal to "foo" then execute the value as true. If it is not equal to "foo" then return false. If it doesn't return either, do not return anything to the user as this may be a glitch in your code or an error.
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
Functions
Bash has functions, though in a somewhat limited implementation. A function is a subroutine, a code block that implements a set of operations, a "black box" that performs a specified task. Wherever there is repetitive code, when a task repeats with only slight variations in procedure, then consider using a function. As in almost any programming language, you can use functions to group pieces of code in a more logical way or practice the divine art of recursion. Declaring a function is just a matter of writing function my_func { my_code }. Calling a function is just like calling another program, you just write its name. Here is a little sample of a function, below the code I will explain what the code does.
PHP Code
<?php
#!/bin/bash
function quit {
exit
}
function hello {
echo Hello!
}
hello
quit
echo foo
This code sets the function quit set as "Exit" which would shut down the script upon the line of code being read by your system. The function hello will echo out "Hello". Now, once we call these functions after declaring them, we will have it say our hello function which is equal to "Hello!" and then after that, we go to our quit function which will exit the script upon the function being called, basic right?
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
User Interfaces(UIs)
Graphical user interfaces (GUI) accept input via devices such as a computer keyboard and mouse and provide articulated graphical output on the computer monitor. You can find these very useful in bash and so do I. So in this step, as in the other steps, I will show you what the code looks like and further explain what the code does. Sounds good? Great.
PHP Code
<?php
#!/bin/bash
OPTIONS="Hello Quit"
select opt in $OPTIONS; do
if [ "$opt" = "Quit" ]; then
echo done
exit
elif [ "$opt" = "Hello" ]; then
echo Hello World
else
clear
echo bad option
fi
done
This code is very basic and is similar to the if statements that we were doing very earlier. So the options are either "HELLO" or "QUIT". This code says if the opt(option) in our variable OPTIONS is "quit" then we will execute the echo "done" and then "exit" which would exit our if statement so the code doesn't carry on to our elif statement. Now, in our elif statement, if it is "HELLO" then it will execute Hello world. If it isn't either of them, the screen will clear.
Command Line(CL)
PHP Code
<?php
#!/bin/bash
if [ -z "$1" ]; then
echo usage: $0 directory
exit
fi
SRCD=$1
TGTD="/var/backups/"
OF=home-$(date +%Y%m%d).tgz
tar -cZf $TGTD$OF $SRCD
What this script does should be clear to you. The expression in the first conditional tests if the program has received an argument ($1) and quits if it didn't, showing the user a little usage message. The rest of the script should be clear at this point. If you understand this, then we are going into the right direction regarding bash.
![[Image: tcXUpiL.png]](https://i.imgur.com/tcXUpiL.png)
User Input
In many occasions you may want to prompt the user for some input, and there are several ways to achive this. This is one of those ways:
PHP Code
<?php
#!/bin/bash
echo Please, enter your name
read NAME
echo "Hi $NAME!"
So this will as for a user input by saying "Please enter your name". Upon a users input, the input will go into the $NAME variable and then once it is read it will echo out the variable after the word "Hi". So it would look something like "Hi Tirus!"
PHP Code
<?php
echo "Do you wish to install this program?"
select yn in "Yes" "No"; do
case $yn in
Yes ) make install; break;;
No ) exit;;
esac
done
With select you don't need to sanitize the input... it prompts you with your choices, and you type a number corresponding to the choice you want. Select also loops automatically... there's no need for a 'while true' loop to retry if they give invalid input. So to explain this code in my own words, it asks you if you wish to install a program. We then set an option for either "y/n == "Yes", "No". If the case is "y" or "Yes", it will make install; break;;. If the case is "No" it will exit the script(Not install the program that you wish to do. Once it runs through those options, if neither is enter Y/N(Yes, No) it will execute "done" which will close the script and "not install the program."



