Bash Shell
{LANG_NAVORIGIN} Reference
What is BASH?
"Bash is a sh-compatible command language interpreter that executes commands read from the standard input or from a file. Bash also incorporates useful features from the Korn and C shells (ksh and csh).
Bash is intended to be a conformant implementation of the IEEE POSIX Shell and Tools specification (IEEE Working Group 1003.2)."
Taken from the BASH manual page, this is an adequate description of the Bourne Again Shell.
BASH is a command interpreter that provides you with an interface to the system. It interprets your commands and performs the relevant system calls to ensure that your command is completed, and a result is returned to an output (usually a screen).
Basic BASH ideas
One of the important features of the BASH command shell is the powerful scripting that is available to you. The focus of this reference sheet shall be on scripting from here on.
Basic BASH scripting
Key commands
echo - To echo text to standard output
cat - Print to standard output anything that is received via standard input. A filename as an argument can also be specified, and the contents of this file will be treated as standard input.
read - Read standard input into a variable
Variable Assignment
In BASH, we can assign variables as
variable=data. Note that no white space is allowed. To reference that variable in future, we refer to it as
$variable.
Example 1
#!/bin/bash
variable="This is test data"
echo My variable is: $variable
Example 2
#!/bin/bash
echo –n "Please enter some text: "
read var
echo You just entered: ${var}…
Note the use of { and } around the variable name. This ensures that the ‘.’s are not included as a variable name.
Flow Control
Now we will look at the if command. This command is self explanatory.
x=1
if [ $x –eq 1 ]; then
echo “x was 1”
else
echo “x wasn’t 1!”
fi
str=”My String”
if [ “$str” == “My String” ]; then
echo “x was My String”
else
echo “x wasn’t My String!”
fi
More information on the if command can be found from the manual pages. –eq is an operator, as are others, including: -gt –lt, etc.. A condition can be negated by inserting the “!” operator before the first variable.
Loops
We will explore two loops here. for loop and the while loop.
ctr=0
for I in “string1” “string2” “string3”; do
let ctr=$ctr+1
echo “Item number $ctr is: $I”
done
ctr=0
max=10
while [ $ctr –lt $max ]; do
let ctr=$ctr+1
echo We have looped $ctr of $max times
done
E-Mail Link
Your IP address will be sent with this e-mail