2. INTRODUCTION
A shell in a Linux operating system takes input from you in the form of commands, processes
it, and then gives an output. It is the interface through which a user works on the programs,
commands, and scripts. A shell is accessed by a terminal which runs it.
Types of Shell
There are two main shells in Linux:
1.The Bourne Shell:The prompt for this shell is $ and its derivatives are listed below:
POSIX shell also is known as sh
Korn Shell also knew as sh
Bourne Again SHell also knew as bash (most popular)
2. The C shell:The prompt for this shell is %, and its subcategories are:
C shell also is known as csh
Tops C shell also is known as tcsh
3. SHELL SCRIPTING
Shell scripting is writing a series of command for the shell to execute. It can
combine lengthy and repetitive sequences of commands into a single and simple
script, which can be stored and executed anytime.This reduces the effort required
by the end user.
For executing the script type bash filename.sh
4. SAMPLE #1 : Variable
Cannot have spaces around your '=' sign.
Can use bash -x scriptname.sh to trace.
Bash variables are untyped.
5. SAMPLE #2 : Variable
scopeVar hasn't been set to any value, so it's blank.
Give it a value
When you call scope.sh from your interactive shell, a new shell is
spawned to run the script.This is partly because of the #!/bin/sh line
at the start of the script.
We need to export the variable for it to be inherited by another
program - including a shell script.
This is changing the value of scopeVar. But there is no way that this
will be passed back to your interactive shell.Try reading the value of
scopeVar .
Once the shell script exits, its environment is destroyed. But
scopeVar keeps its value of hello within your interactive shell.
In order to receive environment changes back from the script, we
must source the script - this effectively runs the script within our
own interactive shell, instead of spawning another shell to run it.
We can source a script via the "." (dot) command
Note that in this case, we don't need to export scopeVar.
6. SAMPLE #1 : Special Variables
There are a set of variables which are set for you already, and most of these cannot have values
assigned to them.
These can contain useful information, which can be used by the script to know about the
environment in which it is running.
The variable $0 is the basename of the program as it was called.
$1 .. $9 are the first 9 additional parameters the script was called with.
The variable $@ is all parameters $1 .. whatever.The variable $*, is similar, but does not
preserve any whitespace, and quoting, so "File with spaces" becomes "File" "with" "spaces".
$# is the number of parameters the script was called with.
Note :
the value of $0 changes depending on how the script was called.
$# and $1 .. $9 are set automatically by the shell.
7. SAMPLE #2 : Special Variables
We can take more than 9 parameters by using the shift command.
$? -This contains the exit value of the last run command. $? will change with every command
that is executed.
The $$ variable is the PID (Process IDentifier) of the currently running shell.This can be useful
for creating temporary files, such as /tmp/my-script.$$ which is useful if many instances of the
script could be run at the same time, and they all need their own temporary files.
The $! variable is the PID of the last run background process.This is useful to keep track of the
process as it gets on with its job.
IFS(Internal Field Separator) -The default value is SPACETAB NEWLINE.
8. SAMPLE #1 : Arrays
Array members need not be consecutive or contiguous.
Some members of the array can be left uninitialized.
Gaps in the array are okay.
Zero-based indexing
Bash permits array operations on variables, even if the variables are not explicitly declared as
arrays. Ex :
string=abcABC123ABCabc
echo ${string[@]} abcABC123ABCabc
echo ${string[*]} abcABC123ABCabc
echo ${string[0]} abcABC123ABCabc
echo ${string[1]} No output!
echo ${#string[@]} 1 # One element in the array. #The string itself.
9. SAMPLE #2 : Arrays
An empty array is not the same as an array with empty elements.
array0=( first second third )
array1=( '' ) # "array1" consists of one empty element.
array2=( ) # No elements . . . "array2" is empty.
Copying an array.
array2=( "${array1[@]}" ) / array2="${array1[@]}"
However, this fails with "sparse" arrays.
11. SAMPLE #1 : Decision Making
[ -a file ] → file exists.
[ -d file ] → file exists and is a directory.
[ -f file ] →file exists and is a regular file.
[ -u file ] →file exists and its SUID (set user ID)
bit is set.
[ -g file ] →file exists and its SGID bit is set.
[ -k file ] →file exists and its sticky bit is set.
[ -r file ] →file exists and is readable.
[ -s file ]→ file exists and is not empty.
[ -w file ]→file exists and is writable.
[ -x file ] is true if file exists and is executable.
[ string1 = string2 ] → the strings are equal.
[ string1 != string2 ] →the strings are not equal.
-eq –> is true if int1 is equal to int2.
-ne –> true if int1 is not equal to int2.
-lt –> true if int1 is less than int2.
-le –> true if int1 is less than or equal to int2.
-gt –> true if int1 is greater than int2.
-ge –> true if int1 is greater than or equal to
int2.
if CONDITION; then
COMMANDS;
else
OTHER-COMMANDS
fi
13. SAMPLE #1 : Loop Control
The break command terminates the loop (breaks out of it).
The break command may optionally take a parameter. A plain break terminates only the
innermost loop in which it is embedded, but a break N breaks out of N levels of loop.
continue causes a jump to the next iteration of the loop.
The continue command, similar to break, optionally takes a parameter. A plain continue cuts
short the current iteration within its loop and begins the next. A continue N terminates all
remaining iterations at its loop level and continues with the next iteration at the loop, N levels
above.
14. SAMPLE #1 : Command
Substitution
Command substitution allows us to take the
output of a command or program (what would
normally be printed to the screen) and save it as
the value of a variable.To do this we place it
within brackets, preceded by a $ sign.
Command substitution is nice and simple if the
output of the command is a single word or line. If
the output goes over several lines then the
newlines are simply removed and all the output
ends up on a single line.
16. SAMPLE #1 :Quoting mechanisms
Strings in bash are sequences of characters.
To create a literal string, use single quotes; to create an interpolated string, use
double quotes
17. SAMPLE #1 : Functions
When writing a suite of scripts, it is often easier to write a "library" of useful functions, and
source that file at the start of the other scripts which use the functions.
A function may return a value in one of four different ways:
I. Change the state of a variable or variables
II. Use the exit command to end the shell script
III. Use the return command to end the function, and return the supplied value to the calling section
of the shell script
IV. echo output to stdout, which will be caught by the caller just as c=`expr $a + $b` is caught
The functions are read in and checked for syntax, but not executed until it is explicitly called.
18. SAMPLE #1 : Regular Expression
Regular expressions are special characters which help search data, matching complex patterns.
Types of Regular expressions :
Basic Regular expressions, Interval Regular expressions, Extended regular expressions
Symbol Descriptions
. replaces any character
^ matches start of string
$ matches end of string
* matches up zero or
more times the
preceding character
Represent special
characters
() Groups regular
expressions
? Matches up exactly
one character
Expression Description
{n} Matches the preceding
character appearing 'n'
times exactly
{n,m} Matches the preceding
character appearing 'n'
times but not more
than m
{n, } Matches the preceding
character only when it
appears 'n' times or
more
Expression Description
+ Matches
one or more
occurrence
of the
previous
character
? Matches
zero or one
occurrence
of the
previous
character
19. SAMPLE #1 : File System
Action Files Folders
Inspect ls ls
View content cat ls
Navigate to cd
Move mv mv
Copy cp cp -r
Create nano mkdir
Delete rm rmdir, rm -r
20. SAMPLE #1 : User Administration
Command Description
sudo adduser username Adds a user
sudo passwd -l 'username' Disable a user
sudo userdel -r 'username' Delete a user
sudo usermod -a -G GROUPNAME
USERNAME
Add user a to a usergroup
sudo deluser USER GROUPNAME Remove user from a user group
finger Gives information on all logged in user
finger username Gives information of a particular user
21. SAMPLE #1 : System Performance
free -m is a command used to show the memory used and free.
‘NR==2’ extracts data form the second line. the $3 and $2 act as holders
for the used and total values respectively.
df -h outputs data related to disk usage and partitions.
awk ‘$NF outputs the number of fields. However, df -h | awk ‘$NF==”/”
will go to that line which contains the character “/”.
The $5 will select the field number five from that line.
This ensures that the command extracts the correct percentage of disk used
The top -bn1 command will execute the top
command only once (n1 = one iteration) the “b” is
used when we want to use “top” in a bash script or to
output its data to a file.
“grep load” will output the line which contains the
string “load”.
$(NF-2) will count the number of fields on that line
and decrement 2, thus outputs field #10.
22. SAMPLE #1 : System Logging
The logger command sends logging messages to the syslogd daemon, and
consequently provokes system logging.
Contents from a file : logger –f filename
23. SAMPLE #1 : IO Redirection
Every process in Unix has access to three input/output channels by default: STDIN (standard
input), STDOUT (standard output) and STDERR (standard error).
When writing to STDOUT, the output appears (by default) at the console.
When reading from STDIN, it reads (by default) directly from what the user types into the
console.
When writing to STDERR, the output appears (by default) at the console.
All of these channels can be redirected.
1:stdout, 2:stderr,
24. SAMPLE #2 : IO Redirection
To dump the contents of a file into STDIN , use the < operator.
To dump the output of a command into a file, use the > operator.
To append to the end of a file, use the >> operator.
To specify the contents of STDIN literally, in a script, use the <<endmarker notation.
To redirect error output (STDERR), use the operator 2>
&>filename – Redirects both stdout and stderr to filename
25. SAMPLE #1 : Signals & Traps
Number Name Description Used for
0 SIGNULL Null Check access to pid
1 SIGHUP Hangup Terminate; can be trapped
2 SIGINT Interrupt Terminate; can be trapped
3 SIGQUIT Quit Terminate with core dump; can be trapped
9 SIGKILL Kill Forced termination; cannot be trapped
15 SIGTERM Terminate Terminate; can be trapped
24 SIGSTOP Stop Pause the process; cannot be trapped
25 SIGTSTP Terminal stop Pause the process; can be trapped
26 SIGCONT Continue Run a stopped process
26. SAMPLE #2 : Signals & Traps
exec 3>&1 4>&2
trap 'exec 2>&4 1>&3’ 0 1 2 3
exec 1>logFile.out 2>&1
# Everything below will go to the file ‘logFile.out’
exec 3>&1 4>&2 - Saves file descriptors.
trap 'exec 2>&4 1>&3’ 0 1 2 3 - Restores file descriptors for particular signals.
exec 1>logFile.out 2>&1 - Redirects stdout to file logFile.out then redirect stderr to stdout.
Are your classroom colors different than what you see in this template? That’s OK! Click on Design -> Variants (the down arrow) -> Pick the color scheme that works for you!
Feel free to change any “You will…” and “I will…” statements to ensure they align with your classroom procedures and rules!