bash shellscripting reminders
Starting
On the first line of your shellscript file, add a comment and a bang and define what shell you want your script to use
#!/bin/bash
Comments
Comments are a hash/pound sign. Everything after that symbol will be ignored (is commented out)
#echo is a command that outputs a specified string to the screen echo "Hello world"
Variables
A variable is a specific label that you can use as a placeholder for an actual value. You can define these on the fly in your code, and you have a series of pre-defined variables, called “environment variables” that you can use directly as they are implicitly part of the script from your shell
Create and use a variable
Enter a unique label that is not one of the environment variables. It generally should not start with $
when being declared and initially set. There must be no spaces between the variable name and it's assignment operator and value. It must start with $
when being used - but not when it is created!
#Define the variable var and load it with a string. Remember no space between the variable, assignment operator and the value to assign. var="Hello World" #Now use that variable echo $var
Command output saved to variable
You can also assign the output of a command to a variable. There are 2 ways of doing this
Assigning output to a variable via slanted quotes
#Get the list of files in the /tmp directory then display them all var=`dir -b /tmp` echo $var
Assigning output to a variable via dynamic variable
#Get the list of files in the /tmp directory then display them all var=$(dir -b /tmp) echo $var
You can use this for example to load values into a for loop, using say a directory listing and parsing each returned element in a list.
Useful environment variables
Environment variable | Description |
---|---|
$HOME | The home directory of the current user. |
$PATH | A semi-colon delimeted list of all paths that the shell will search when looking for an executable file. |
$PS1 | A variable containing the symbol(s) that will be shown at the primary command prompt |
$PS2 | A variable containing the symbol(s) that will be shown at the secondary command prompt |
$IFS | A list of characters that the shell considers as delimeters when reading parameters to a program call. Usually contains a space, a tab, and a newline character. |
$0 | The name of the current shell script, in the context of how it was invoked. |
$# | The number of parameters passed to the current shell script |
$1 , $2 , $3 …. | The parameters passed into the current script, in the order of passage |
$$ | The PID (process ID) of the current script. |
For loop
You can run commands in a loop. This is useful for example when you want to do something on individual files in a directory for instance:
Basic loop
for i in 1 2 3 4 5 6 7 8 9 10; do echo $i; done;
You can load the in part of the loop with a regular expression or with the output of a command line tool.
Using a regex to repeat a string
The output of this snippet is identical to the snippet above.
for i in {1..10}; do echo $i; done;
Using the output of a command line tool
There are 2 ways of doing this, by encapsulating the command within slanted quotes or encapsulating the command in a sort of dynamic variable.
In this example, the dir
command will list file in a given directory, and these are loaded one at a time as a list into i
which can then be used to output a filename or use as a value for another command line tool, such as grep
for i in `dir -b /tmp`; do echo $i; grep "something" $i; done;
Conditional execution - if/then/else
An if
structure will allow you to check if a value matches a specific condition, then runs the code defined in that section. You can add multiple conditions to check in an if
, or as an “elseif” structure, called elif
, and you may define an else
structure to do something if nothing else matches the conditions you set. In this case, remember to space out the operators in the condition block.
Remember:
- Always put the
then
condition on a new line after your comparison condition - An
if
condition always ends with the opposite:fi
.
if with single comparison value
val=1; if [ $val = 1 ] then echo "val is 1"; fi
if with multiple comparison values
Use the equivalence operator -eq
for “equals”, and the logical-OR operator (the logical operators are same as in the C language), so here ||
, add comparison blocks separated each by whatever needed logical operators.
val=1; if [ $val -eq 1 ] || [ $val -eq 2 ] then echo "val is 1"; fi
If/else
Checking the value of a command line argument sent to the script as the scripts first argument, check if it equals 1
or if it's something else:
val=$1; if [ $val -eq 1 ] then echo "val equals 1" else echo "val does not equal 1" fi
if/else if/else
This introduces the elif
structure, which works the exact same way as if allowing you to match several different values in a condition:
val=$1; if [ $val = 1 ] then echo "Val = 1"; elif [ $val = 2 ] then echo "Val = 2"; elif [ $val = "Hello" ] || [ $val = "World" ] then echo "Somebody typed Hello or World; else echo "No matching values were entered" fi
Condition comparison statements
String Comparison | Description |
---|---|
Str1 = Str2 | Returns true if the strings are equal |
Str1 != Str2 | Returns true if the strings are not equal |
-n Str1 | Returns true if the string is not null |
-z Str1 | Returns true if the string is null |
Numeric Comparison | Description |
expr1 -eq expr2 | Returns true if the expressions are equal |
expr1 -ne expr2 | Returns true if the expressions are not equal |
expr1 -gt expr2 | Returns true if expr1 is greater than expr2 |
expr1 -ge expr2 | Returns true if expr1 is greater or equal to expr2 |
expr1 -lt expr2 | Returns true if expr1 is less than expr2 |
expr1 -le expr2 | Returns true if expr1 is less or equal to expr2 |
! expr1 | Negates the result of the expression (not expr1 ) |
File Comparison | Description |
-d file | True if the file is a directory |
-e file | True if the file exists (note that this is not particularly portable, thus -f is generally used) |
-f file | True if the provided string is a file |
-g file | True if the group id is set on a file |
-r file | True if the file is readable |
-s file | True if the file has a non-zero size |
-u | True if the user id is set on a file |
-w | True if the file is writable |
-x | True if the file is an executable |
Logical operators
- AND:
&&
- OR:
||
Read input from the command line
You will use the read instruction that will pause execution until something is entered interactively on the command line and enter is pressed. The entered value will be pushed into a variable that follows the command, here input captured by read will be saved into the userInput
variable:
echo "Enter something and press enter" read userInput echo $userInput
Quotes
There are 2 types of quotes used to encapsulate strings in Shell Script: Single and double.
Single quotes
Single quoted strings are used where data needs to be output literally, including names of variables rather than their values
Double quotes
Double quoted strings are used where variables need to be displayed as their actual variable value
Quote Example
val="Hello World" echo 'this will display $val' #outputs this will display $val echo "this will display $val" #outputs this will display Hello World