Bash Scripting Flashcards
What is bash?
Bash is a command language interpreter. It is widely available on various operating systems and is a default command interpreter on most GNU/Linux systems. The name is an acronym for the ‘Bourne-Again SHell’
What is shell?
Shell is a macro processor which allows for an interactive or non-interactive command execution
What is scripting?
Scripting allows for an automatic commands execution that would otherwise be executed interactively one-by-one
YouTube Tutorial (NetworkChuck)
nano = a text editor (to save the script to)
#! = a shebang
/bin/bash to tell linux to use bash for scripting (as opposed to e.g python or another scripting language)
Always start a bash script with a #!/bin/bash
To create a basic echo script using nano as the text file:
step 1. nano ‘create file name’ so e.g write: nano HelloBlossom.sh
Step 2. now you are in the file you create the script so type: #!/bin/bash and enter
Step 3: now create the commands (e.g echo and sleep commands)
Step 4. Once we have created the script we save it as a .sh file. To get out of nano press ctrl X. It will ask if we want to save it. We say ‘y’ for yes. It then asks if you want to save it with that file name. Use Y again for yes.
Then you can check that you do have a script there that we wrote / saved correctly use command ls to see it (ls lists files and directories within the file system)
Step 5. Run it. To run the script type bash then a space then your script file name (e.g HiBlossom.sh) so in that example would be: bash HiBlossom.sh
Step 6. To make it an executable file type chmod +x HiBlossom.sh
(chmod lets us change permissions the x means executable permissions r means read permissions w means write permissions)
To check file permissions use ls -l
Now you can RUN / EXECUTE the script using command ./ before the file name e.g ./HiBlossom.sh
What are variables?
A variable is something that you want to change or vary in your script.
Open the ‘bestdayever.sh’ for this example
Use the dollar sign $ in your script to indicate where you want the variable to be for example echo “Good morning $name” and at the top of the nano file specifiy what name is e.g name=”Carly”
So if you had 10 instances on where you want the script to say ‘Carly’ sometimes, but sometimes ‘Lee’ you would use the $name variable instead of Lee or Carly and you only have to change the variable once each time in the name=”Carly” bit instead of 10 times within the script.
BUT what if you want the script to use the name of whoever is using the computer.
Use ‘read’ to get some user input at the top of your script instead of putting what name equals. So at top of script put:
echo “What is your name?”
read name
This means the name variable now becomes whatever the user inputs as the answer to what is your name
What is an argument?
Use $1 as your first positional argument (parameter). So to get the script to run with the name Blossom in you would put the following at the top of your script:
name=$1
then the script with the name in but when you run it type:
./bestdayever.sh Blossom
Whatever the first thing you write after the ./bestdayever is the first positional argument ($1)
Some basic Linux Commands and how to use them in variables
whoami: Who am I logged in as
pwd: print working directory = where am I in my file system right now
date: displays date
so when we want to put the output of a command in as a variable put it in brackets. e.g user=$(whoami)
Using the $RANDOM variable
the RANDOM variable is inbuilt in linux. It randomly generates a number between 0 and 32767.
You can change the range of numbers that this variable generates by using arithmetic expressions (which basically means using bash to do maths)
To do this put the expression (the maths)$ in double brackets $((the maths you want it to do))
e.g $(( 2 + 3 ))
so to change the random variable use the modulo sign %
$(( $RANDOM % 20 )) will make the RANDOM variable chose a number between 0 and 19 (ecause you have told it to chose 20 digits)
There are others inbuilt in linux (called internal shell variables) like $SHELL (tells us what shell we are using)
$USER (tells us what user we are)
$PWD (tells us where we are in the directory)
$HOSTNAME (tells us the name of the host - i.e the name of our device)
$BASH_VERSION (tells us what evrsion of bash we are using.
Creating your own system variables
You can create your own in built variables
Type the name of the variable then “whatyouwantittobe”.
So to create a variable called ‘dog’ that you want to equal ‘Alfie’
type: dog=”Alfie” and enter
then to set it into the system type:
export dog
then use it in your script e.g echo “your dog is called $dog”
but it will not be permanent to use next time unless you edit the bashrc file
So use nano to edit it by typing nano .bashrc
(in Linux files with a dot in front of it are ‘hidden’ on the system)
Never name your own variables IN UPPERCASE LETTERS! These are reserved for internal shell variables
How can you add programmer’s internal notes in a bash script?
Use a hashtag symbol.
Every line starting with # sign (except shebang) will not be interpreted by bash and will only serve as a programmer’s internal note.
Standar Error Output & Standard Output
A standard error output (stderr) is when the output of a command is an error. i.e you get an error message
A standard output (stdout) is when the output is expected and an ouput is given.
The difference between stdout and stderr output is an essential concept as it allows us to redirect each output separately.
The > notation is used to redirect stdout to a file
whereas 2> notation is used to redirect stderr and
&> is used to redirect both stdout and stderr
An example:
Back to our backup.sh script. When executing our backup script, you may have noticed an extra message display by tar command:
tar: Removing leading `/’ from member names
Despite the message’s informative nature, it is sent to stderr descriptor. In a nutshell, the message is telling us that the absolute path has been removed thus extraction of the compressed file not overwrite any existing files.
Now that we have a basic understanding of the output redirection we can eliminate this unwanted stderr message by redirecting it with 2> notation to /dev/null. Imagine /dev/null as a data sink, which discards any data redirected to it.
Input Descriptor - stdin
Apart of the above stdout and stderr descriptors bash shell also features input descriptor name stdin. Generally, terminal input comes from a keyboard. Any keystroke you type is accepted as stdin.
The alternative method is to accept command input from a file using < notation. Consider the following example where we first feed cat command from the keyboard and redirecting the output to file1.txt. Later, we allow cat command to read the input from file1.txt using < notation:
Functions
Functions allow a programmer to organize and reuse code, hence increasing the efficiency, execution speed as well as readability of the entire script.
You can think of the function as a way to the group number of different commands into a single command. This can be extremely useful if the output or calculation you require consists of multiple commands, and it will be expected multiple times throughout the script execution.
Functions are defined by using the function keyword and followed by function body enclosed by curly brackets
Quick Tip:
The moment you notice that your script contains two lines of the same code, you may consider to enact a function instead.
It is important to point out that the function definition must precede function call, otherwise the script will return function not found error
What is indentation?
Indentation is a technique used so it is much clearer to see specific areas of code for example when using a function. There is no general convention on how to indent bash script thus it is up to each individual to choose its own way to indent. Our example used TAB. However, it is perfectly fine to instead a single TAB use 4 spaces, etc.