0% found this document useful (0 votes)
26 views

Scripting Languages M2

This document provides an introduction to shell scripting using bash. It discusses: 1. What shell scripting is and how it allows users to automate tasks and create custom tools. 2. The basics of bash scripting, including common commands, variables, control structures, and how each keyword is actually a program executed by the bash shell. 3. How to write and execute a simple "Hello World" bash script as an example, including setting execute permissions and invoking the script.

Uploaded by

vibaviattigala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Scripting Languages M2

This document provides an introduction to shell scripting using bash. It discusses: 1. What shell scripting is and how it allows users to automate tasks and create custom tools. 2. The basics of bash scripting, including common commands, variables, control structures, and how each keyword is actually a program executed by the bash shell. 3. How to write and execute a simple "Hello World" bash script as an example, including setting execute permissions and invoking the script.

Uploaded by

vibaviattigala
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Scripting Languages

Module 2
Introduction to Shell Script (bash)
Learning Objectives

By the end of this Module you will :


• Know the basics of shell script
• Be aware of the many commands and
utilities you can use in your scripts
• Use the bash shell to perform simple
tasks on your computer
• Write and execute simple bash scripts
What is shell script?
What is Shell Scripting?
• A shell script is a series of
commands aggregated within a
single structured file
• A command shell executes this file
line-by-line, one command at a time
as if individually executed on the
command line
• A shell script may use control
structures, variables and dynamic
inputs to control how and when
commands are executed
A simple shell script that allows the user to backup
• In this sense, shell scripting is a a given file to a given directory
form of computer programming
What is Shell Scripting?
• Shell scripts allow users to automate
repetitive, multi-step tasks and often
complex tasks on a Linux installation
• Shell script is also used to create custom
tools designed to perform highly specific
tasks for which no pre-made solution is
available
• Scripts are usually designed to be executed
in a command-line interface, although they
can be triggered in other ways, e.g. a
scheduled chron job
Working with the
bash shell
Bash Scripting in the Bash Shell

• In this unit, you will write shell


scripts for bash, which is short
for the Bourne again shell
• The bash shell is base on earlier
shell version used in Unix-like
systems called the Bourne shell,
or sh for short
• Think of the bash shell as the
glue that binds a vast collection
of Linux commands together
Bash Scripting in the Bash Shell
• bash is compatible with sh
commands and scripts
• It provides a more modern
interface and advanced features
• Each keyword used in bash
scripting is actually a program
• Even control structures such as
while or if are actually
executable programs being run
by the bash shell
bash CLI vs Linux GUI

Any task that can be


accomplished by a Linux GUI
such as creating folders and
editing files…

…can also be accomplished


using the bash CLI by executing
a bash script in the bash shell.
Shell Script
Commands
Common bash Commands

NAME CLASS OPERATION

awk utility Non-compiled scripting language utility used for simple to complex
data manipulation data and report generation
basename command Strips directory and suffix from filenames
bc utility Arbitrary precision calculator language
cat command Concatenate and print (display) the content of files
chmod command Change access permissions to files and folders
clear command Clear terminal screen of all text
cp command Copy one or more files/folders to another location
cut command Rules-based division of a file’s or variable’s argument resident data

date command Extract, display or change the date/time values


declare keyword Declare variables or arrays with pre-defined data types an attributes

df command Display free disk space on a storage volume


diff command Analyses two files and outputs those lines that are differ
du command Estimate file space usage of a file or system volume
Common bash Commands

NAME CLASS OPERATION


echo command Display textual output to the terminal
eval command Evaluate and execute multiple commands/arguments in-situ
exit command Exit the shell
expand command Convert tabs to spaces in a file
expr command Evaluate stated expressions and returns a result
false keyword Indicate false result to test, or to do nothing
file command Determine file type of argument supplied
find command Search for files that meet a desired criteria
for keyword Indicates to execute commands on items in file or array one-by-one

grep utility Search file(s) for lines that match a given pattern
if keyword Conditionally perform a command
Common bash Commands

NAME CLASS OPERATION


let keyword Perform arithmetic on shell variables
local keyword Create a function variable
ls command List information about file/folders
man command Help manual
mkdir command Create/make a new directory (folder)
mv command Move or rename files or directories
printf command Format and print data to output, e.g. terminal, file, variable
pwd command Prints path to Working Directory to terminal or other output
read keyword Read a line from standard input
return keyword Exit a shell function, usually with a return value
rev command Reverse lines of a file
rm command Remove files/folders
rmdir command Remove folder(s) (only if empty)
Common bash Commands

NAME CLASS OPERATION


sed utility Stream Editor, a.ka. search and replace
seq command generate numbers from FIRST to LAST in steps of INCREMENT

shuf command Generate random permutations of provided arguments


sort command Sort text files according to stipulated criteria
tee command Redirect output to multiple outputs, e.g., terminal and file
test keyword Evaluate a conditional expression
touch command Create a new file or update an existing file's timestamp
tr command Translate, squeeze, and/or delete characters
true keyword Indicate true result to test, or trigger to do something
uniq command Filters out duplicate items in a file
unset keyword Remove variable or function names
until keyword Indicates command execution until a criteria is no longer true
wc command Count the bytes, words, or lines in a file or variables contents
which command Search the user's $path for a program file
while keyword Indicates command execution until a criteria is no longer false
Shell Script Editors
Text Editors

• Text editors are used to create and edit scripts


• Different programmers vary in which text editor they prefer
• Some are text based and others graphically based
• Text-based script editors include VI or ViM, nano and emacs
and are used in server environments where no GUI is available
• Graphical-based script editors include VS Code, gedit, Atom
and sublime and are often used in desktop development
environments where a GUI is available
• In this unit, the VS Code development environment will be
provided within a Ubuntu virtual machine
VS Code

• Visual Studio Code is a cross


platform text editor made by
Microsoft
• It is not to be confused with
the Visual Studio IDE
• VS Code is designed to be a
light-weight, cross platform
editor for development
• Additional features can be
added through custom
extensions
Writing a bash
shell script
The Hello World Script

• Most programming beginners


start out by writing a simple
program to output the words
Hello World on the screen
• In bash scripting, this can be
accomplished with the script
shown to right
The Hello World Script

#!/bin/bash The #!/bin/bash comment tells Linux to use bash


echo "Hello World!" when interpreting the script as opposed to another
exit 0 interpreter such as required by php, perl or python
The echo command is a built-in shell command used
to write its argument to a standard output
The standard output, a.k.a. stdout prints the
argument to the terminal screen by default
The information to be printed is enclosed in double
quotes “Hello World” which tells the system
specifically what is to be sent to stdout
exit 0 is an error status code that means the script
has executed successfully without error
Executing the script
• In most operating systems, files are
not allowed to be directly executed
as scripts by default
• Most scripts will need to have the
correct permissions set to allow
them to be executed $ bash hello1.sh
• A script without the execute
permissions can be manually
executed by invoking the bash
command but this is not ideal
Executing the script

• Permissions can be set using the chmod command


• $ chmod +x hello1.sh or
• $ chmod 777 hello1.sh
• This only needs to be done once.
• After the file is marked as executable, the script can
be run by prepending it with ./ and hitting Enter
• $ ./hello1.sh
Writing and Executing a bash Script
Using the VS Code development environment

Shell Script

Commands to create
~/CSI6203/
~/CSI6203/
shell script file, make it
~/CSI6203/ executable and run it
~/CSI6203/

~/CSI6203/
Working with variables
and arguments
Variables
• Information in bash scripts can be stored in variables
• Once information is stored in a variable, it can be called upon in
the script by invoking the variable’s name
IMPORTANT NOTE:
When you declare a variable
and/or assign it an argument,
you do so without the $
prepend, as shown in the yellow
boxes. However, when you call
upon a variable to use its
argument in the code, you must
use the $ prepend in each case
as shown in the blue boxes.
Passing Arguments to Default Variables
• There are some special variables that are used for receiving input from
the command line as they are executed
• Each argument typed into the command line is referred to by a special
numeric variable
Special Argument
Variable
$ ./hello.sh Tom $0 Holds the name of the script being run
Hello Tom
$1, $2, $3 Arguments passed along with the running of the
etc script on the command line, e.g. myscript.sh 20
#!/bin/bash 30 40 - $1 is the first argument, i.e. 20, $2 the
echo "Hello $1!" second arguments, i.e 30 and $3 is the third
argument, i.e. 40 ..and so on
$# Holds the number of arguments passed to the
script
$? Holds the last output of the script
Note: This can change constantly as the script
executes
Arguments

• The following variables are available to handle arguments


• These can be used to print custom messages or get the name of the
script

Argument Name Purpose

$0 The name of the script file

$1 The first argument sent to the script

$2 The second argument sent to the script

$# The number of arguments sent to the script

$* All the arguments sent to the script


References and Resources

▪ Ebrahim, M., & Mallett, A (2018). Mastering Linux Shell scripting:


A practical guide to LInux command-line, Bash scripting, and
Shell programming (2nd Ed.). Birmingham UK: Packt.
▪ An A-Z Index of the Linux command line: bash + utilities. Available at
SS64.com
▪ Bash Reference Manual. Available at https://www.gnu.org/savannah-
checkouts/gnu/bash/manual/bash.html
Terms to Review and Know

• Shell scripting
• Bash shell and scripting
• Text Editors
• Variables
• Git and github.com

You might also like