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

420-N23_Operating_Systems_-_Topic_14_-_Scripting_I (1)

The document provides an overview of Bash scripting, explaining how to create and execute scripts, use variables, and perform operations such as string concatenation and command substitution. It covers best practices for naming scripts, the significance of special variables, and includes exercises for practical application. Additionally, it introduces control structures like loops and conditional statements, culminating in a final lab challenge involving a FizzBuzz program.

Uploaded by

Chris Peterson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

420-N23_Operating_Systems_-_Topic_14_-_Scripting_I (1)

The document provides an overview of Bash scripting, explaining how to create and execute scripts, use variables, and perform operations such as string concatenation and command substitution. It covers best practices for naming scripts, the significance of special variables, and includes exercises for practical application. Additionally, it introduces control structures like loops and conditional statements, culminating in a final lab challenge involving a FizzBuzz program.

Uploaded by

Chris Peterson
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 38

420-N23-LA

Operating Systems &


Scripting Using Linux
SCRIPTING I

©2020 Brendan Wood


Bash Scripts
Anything you can run normally on the command line can
be put into a script and it will do exactly the same thing.
Similarly, anything you can put into a script can also be run
normally on the command line and it will do the same
thing.
Best Practice: Use underscores to use multiple words In a
script name.
find_broken_files.sh
Scripts
A script is NOT a traditional program. A program needs to be compiled into binary code and
executed. Scripts will run commands in a sequence, no compiling necessary.
You need to tell the script what kind of script it is, in the FIRST LINE.
#!/bin/bash
You must make sure the file is EXECUTABLE to run it. (Use CHMOD).
-rwxr--r-- 1 bwood bwood 274 Apr 2 20:26 helloWorld1.sh
chmod u+x, g+x filename.sh
Note: A script spawns a new instance of a bash shell to run into it. So it is “on it’s own”. That
means all it’s variables and values are isolated in it’s own shell.
Example Script
script1.sh
#!/bin/bash
# This script tells us what is the meaning of life!
echo The meaning of life is 42.

./script.sh #Runs it
Comments on previous script
# is a comment.
./ runs the script.
Why? Because when we issue a command to run, the bash shell looks at your PATH, NOT your
immediate surrounding!
Try it: echo $PATH
The ./ command means:
◦ Dot : Current directory
◦ Slash : “In the Current Directory”
Alternative: Use absolute path to your script. ~/scripts/myscript.sh
Variables
When referring to or reading a variable we place a $ sign before the
variable name.
When setting a variable we leave out the $ sign.
It is suggested to use “camelCase” to name your variables. Otherwise
consider using lowercase words separated by underscores.
this_is_a_variable
A variable may be placed anywhere in a script (or on the command
line for that matter) and, when run, Bash will replace it with the value
of the variable. This is made possible as the substitution is done
before the command is run.
Variables …
Remember to use quotes when assigning complex strings with spaces.
Also remember not to use spaces AT ALL.
my_variable=“This is a string”
my_variable2=This is another string

We were able to echo “The meaning of life is …” without quotes but that is ECHO not variable
assigning!
Single and double quotes
Just like in PHP, we treat single and double quotes differently.
“Things in here are PROCESSED”
‘Things in here are NOT PROCESSED”.

var1=“ABC”
echo “The value is $var1” # The value is ABC
echo ‘The value is $var1’ # The value is $var1
Concatenating strings
Method 1
foo="Hello"
foo="$foo World"
echo $foo

Method 2
a='hello'
b='world'
c=$a$b
echo $c
Running commands WITHIN ECHO
METHOD 1
Anything between the "tick" characters is executed like a real command and it's output is
returned.
You can run a command in echo like this:

echo “Your home directory is currently `pwd` “


Your current directory is /home/bwood

Can you figure out how to display:


The date is Fri Apr 10 00:45:21 EDT 2020
Running commands WITHIN ECHO
METHOD 2
Anything between the$(……) characters is executed like a real command and it's output is
returned.
You can run a command in echo like this:

echo “Your home directory is currently $(pwd)“


Your current directory is /home/bwood

Can you figure out how to display:


The date is Fri Apr 10 00:45:21 EDT 2020
Command Substitutions
A variable can contain a command within it.

myCommand=$( date )
Echo “The date is : $myCommand”
Exercise 1
Write a your first program.
Set two variables; $name and $favouriteNumber
Name = Your Name
Favourite Number = 42
Display the line “Hello, my name is Brendan and my favourite number is 42.”
Remember to set the bash type, and the execution bits.
Special Variables
$0 - The name of the Bash script.
$? - The exit status of the most recently run process.
$$ - The process ID of the current script.
$USER - The username of the user running the script.
$HOSTNAME - The hostname of the machine the script is running on.
$SECONDS - The number of seconds since the script was started.
$RANDOM - Returns a different random number each time is it referred to.
$LINENO - Returns the current line number in the Bash script.

Try these to discover what they return.


Expressions
Arithmetic Expression is used like this: $((Expression))

num_three=$((1+2))
num_whatever=$((num1 + num2))

Floating point expressions:

num=$(python -c "print $num1+$num2")


Expressions … another way
x = 42
y = 15
let z=“$x + $y” # 57
echo $z
Parameters
More special bash script variables:
$1 - $9 - The first 9 arguments to the Bash script.
$# - How many arguments were passed to the Bash script.
$@ - All the arguments supplied to the Bash script.

To read a parameter, access it using the $1 or $2 variables.


Use it in conjuction with $# if necessary.
Files in Parameters
TIP:
You can also pass filenames in your parameters.
Suppose you want to make your own file mergeutil, something easy.

./merge.sh ./file.txt ./file2.txt

#!/bin/bash
# A simple copy script
cat $1 $2 >> result_$1
# Let's verify the copy worked
echo file $1 concatenated to $2 successfully.
Exercise 2a
Rewrite exercise 1 using parameters.
I can run it like this:
./myscript.sh Brendan 42
Question: How can I pass my full name to the script? Brendan Wood?

Tip: you can also write


bash myscript.sh Brendan 42
Exercise 2b
Create a program that takes in two parameters, which should be numbers,
and adds them.
It should give a message like:
The sum of 4 and 5 is 9

Pretend it’s a perfect world and people will enter EXACTLY 2 numbers.
Exercise 3 (Practice question)
Tell me how many files are in the current directory (in a script) by
using commands in a variable?
Hint:
wc will count lines.
ls –1 will output n lines.
Class Question
What will this output?
1) I log into Linux
2) I write this:
◦ myName=“Brendan”

3) I then run a script (./script.sh) containing this:


#!/bin/bash
echo “Welcome back $myName”
Variable scope
Variables are local to each bash process.
Variables created in my shell, stay there– invisible to other processes.
Variables in my bash shell script live and die in the script.
UNTIL NOW
If we EXPORT the value, it becomes common to all.
Scope
Unset
◦ Erases the variable and its value

Export
◦ Makes variables available to any children of this shell

Readonly
◦ Any program other than this shell can only read the value and not modify it
More special variables
$HOME Your home directory
$PATH The path we look for executable programs or scripts
$PS1 Your command prompt string
$PWD Current working directory
$SHELL Full path to your shell
Console IO
Read
◦ Read a value from the keyboard

read -p “How old are you?” age

echo “You are $age years old”

This is beyond the scope of the course, but you can use printf to print using automatic formatting and
variable placement.

printf “You are %4s years old” $age


Multiple Console Input
Read item1 item2 item3
This can read an input string like : a b c
So that
Item1 = a
Item2 = b
Item3 = c
LAB CHALLENGE 1
Write a copy utility that will create a dated archive copy of a file.
Example:
datedCopy.sh file1.txt

Result: 2 files
file1.txt
018-04-02_22:49:11_file1.txt

A hint: date '+%Y-%m-%d_%H:%M:%S'


Your First Loop
while [<some test>]
do
<commands>
done
The operators used
-lt (<)
-gt (>)
-le (<=)
-ge (>=)
-eq (==)
-ne (!=)
Example of a While Loop
#!/bin/bash
# Basic while loop
counter=1
while [ $counter -le 10 ]
do
echo $counter
((counter++))
done
echo All done
Lab CHALLENGE
Create the following output with a while loop:

*
**
***
****
*****
IF statement
if [ <test> ] if [ $1 -gt 100 ]
Then then
<commands> echo A large number.
else else
<more commands> echo Not a large number.
fi fi
IF TESTS
! EXPRESSION The EXPRESSION is false.
-n STRING The length of STRING is greater than zero.
-z STRING The lengh of STRING is zero (ie it is empty).
STRING1 = STRING2 STRING1 is equal to STRING2
STRING1 != STRING2 STRING1 is not equal to STRING2
INTEGER1 -eq INTEGER2 INTEGER1 is numerically equal to INTEGER2
INTEGER1 -gt INTEGER2 INTEGER1 is numerically greater than INTEGER2
INTEGER1 -lt INTEGER2 INTEGER1 is numerically less than INTEGER2
-d FILE FILE exists and is a directory.
-e FILE FILE exists.
-r FILE FILE exists and the read permission is granted.
-s FILE FILE exists and it's size is greater than zero (ie. it is not empty).
-w FILE FILE exists and the write permission is granted.
-x FILE FILE exists and the execute permission is granted.
If..elif..else..fi
If [ conditional expression1 ]
then
statement1
statement2
elif [ conditional expression2 ]
then
statement3
statement4
else
statement5
fi
Final LAB CHALLENGE (3)
Using while loop(s) do this:
Loop from 0 to 100

1. For each value that can be divided by 3, print “n: Fizz”.


2. For each value that can be divided by 5, print “n: Buzz”.
3. For each value that can be divided by both, print “n: FizzBuzz”.
FizzBuzz output
1: -
2: -
3: Fizz
4: -
5: Buzz

15: FizzBuzz
End
SLIDE SET 10

You might also like