Module 11 Basic Scripting
Exam Objective
3.3 Turning Commands Into Scripts
Objective Description Turning repetitive commands into scripts
Introduction
Introduction
● A shell script is a file of executable commands that have been stored in a text file.
● When a script file is run, each command in it is executed.
● Building shell scripts helps to automate repetitive parts of your work.
Simple Script
Simple Script
● Example of a script with only one command: echo “Hello, World!”
● Running a script can be done either by typing it as an argument to your shell:
● Or by running the file directly:
sysadmin@localhost:~$ sh test.sh Hello, World!
sysadmin@localhost:~$ ./test.sh -bash: ./test.sh: Permission denied
The error Permission denied means that the script has not been marked as executable. The command can be used to change the permissions of the file.
chmod
Simple Script
● Complicated scripts will indicate a particular shell:
echo “Hello, World!”
#!/bin/sh
○ #! (shebang) is a prefix that marks following text as executable ○ /bin/shspecifiestheabsolutepathtotheinterpreter
Editing Shell Scripts
● Shell scripts are written using plain text.
● Becoming familiar with text editors helps with writing shell scripts.
○ The GNU nano editor is a simple editor well suited for editing small text files.
○ The Visual Editor, vi, or its newer version, VI improved vim, is a remarkably powerful
editor.
○ A simple script in nano would look like the following:
GNU nano 2.2.6 File: test.sh modified
#!/bin/bash
echo “Hello, World!” echo -n “the time is ” date
Scripting Basics
Scripting Basics
● Recall, the script started with the shebang (#!) line, telling Linux that the Bash shell is to be used to execute the script.
● Other than running commands in scripts, there are 3 topics you must become familiar with:
○ Variables, which hold temporary information in the script
○ Conditionals, which let you do different things based on tests you write
○ Loops, which let you do the same thing over and over
Variables
● Variables are a key part of any programming language.
● A very simple use of variables is shown here:
#!/bin/bash
ANIMAL=”penguin”
echo “My favorite animal is a ”
$ANIMAL
○ The variable name is ANIMAL and the equals sign assigns the string penguin.
○ To access the contents of the variable, prefix it with a dollar sign $.
■ When the interpreter sees the dollar sign, it recognizes that it will be substituting the contents of the variable, which is called interpolation.
Variables
● Another way to assign to a variable is to use the output of another command as the contents of the variable by enclosing the command in backtick ` characters.:
#!/bin/bash
CURRENT_DIRECTORY=`pwd`
echo “You are in $CURRENT_DIRECTORY”
● It is also possible to get input from the user of the script and assign that input to a variable using the read command:
#!/bin/bash
echo -n “What is your name? ”
read NAME
echo “Hello $NAME!”
Variables
● There are also special variables. The $0 variable contains the name of the script itself. Additionally, you can pass arguments to your script:
#!/bin/bash
echo “Hello $1”
○ A dollar sign followed by a number N corresponds to the Nth argument passed to the script. If you use the above script and run it with Linux as the first argument, the output will
be Hello Linux.
sysadmin@localhost:~$ ./test.sh Linux Hello Linux
Variables
● After a program runs it returns an exit code which is an integer between 0 and 255.
● This can be tested through the $? variable to see if the previous command completed successfully. The grep command returns 0 if the string was found and 1 otherwise.
#!/bin/bash
echo “Hello $1”
sysadmin@localhost:~$ grep -q root /etc/passwd sysadmin@localhost:~$ echo $?
0
sysadmin@localhost:~$ grep -q slartibartfast /etc/passwd sysadmin@localhost:~$ echo $?
1
● You can also set the exit code of your own script with the exit command.
#!/bin/bash
# Something bad happened!
exit 1
Conditionals
● You can make your script do different functions based on tests, called branching.
● The if statement is the basic operator to implement branching.
● A basic if statement looks like this:
if somecommand; then
# do this if somecommand has an exit code of 0
fi
○ If the exit code is 0 then the contents up until the closing fi will be run.
Conditionals
● The test command gives you easy access to comparison and file test operators. ○ For example, the -f operator to the test command checks if the file exists:
■ test –f /dev/ttyS0 – Will test if file exists
■ test –d /tmp – Will test if directory exists
if test –f /tmp/foo; then if [ -f /tmp/foo]; then
Conditionals
● The if statement has a final form that lets you do multiple comparisons at one time using elif (short for else if).
#!/bin/bash
if [ “$1” = “hello” ]; then
echo “hello yourself”
elif [ “$1” = “goodbye” ]; then
echo “nice to have met you”
echo “I hope to see you again”
else
echo “I didn’t understand that”
fi
○ If the first argument passed to the script is hello, the first block is executed. If not, the script checks to see if it is goodbye and echos a different message if so. Otherwise, a third message is sent.
Conditionals
● The case statement provides a different way of making multiple tests easier.
#!/bin/bash
case “$1” in
hello|hi)
echo “hello yourself”
;; goodbye)
echo “nice to have met you”
echo “I hope to see you again”
;;
*)
echo “I didn’t understand that”
esac
○ The case statement starts off with a description of the expression being tested: case EXPRESSION in.
○ Next, each set of tests are executed as a pattern match terminated by a closing parenthesis.
○ Following that are the commands to be executed if the pattern returns true, which are terminated by two semicolons.
○ The * pattern is the same as an else because it matches anything.
Loops
● Loops allow code to be executed repeatedly.
● There are two main loops in shell scripts: the for loop and the while loop.
○ for loops are used when you have a finite assortment, such as a list of files, over which you want to iterate (repeat and execute code).
○ A while loop, operates on a list of unknown size.
Loops
● In the example below, a for loop “loops” over the list of servers:
#!/bin/bash
SERVERS=”servera serverb serverc” for S in $SERVERS; do
echo “Doing something to $S”
done
○ The SERVERS variable stands for the list of servers (servera serverb serverc).
○ Each time it sets the S variable to the current server name.
Loops
● A while loop keeps running and on each iteration perform a test to see if it should run another time.
● In other words, “while some condition is true, do something.”
#!/bin/bash
i=0
while [ $i -lt 10 ]; do
echo $i
i=$(( $i + 1))
done
echo “Done counting”
○ The example above shows a while loop that counts from 0 to 9. ○ A counter variable, i, is initialized to 0.