You are on page 1of 50

UNIX

BASH Programming (Part 1)

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

1 of 50

UNIX
BASH Programming
Topics:

Shells
Running a BASH Script
Shell Variables and Related Commands
Passing Arguments to Shell Scripts
Program Control Flow Commands (if)
Arithmetic Operators

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

2 of 50

Shell Scripts
The shell script is a file that contains series of commands
to be executed by the shell.
There are three ways to execute Bash shell script:
o By making the shell script file an executable file using
chmod command,
o By running the /bin/bash command with the script file as
its parameter (/bin/bash script_file), or
o Begin a shell script with #!/bin/bash.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

3 of 50

Command: echo

Purpose
Flags
\b
\c
\f
\n
\t

echo[flags][file-list]
Print-to-screen function
Moves already printed text back one space.
Forces the following command to appear on the same
line as the current command.
Forces the following command to appear on the next
line at a specified horizontal location.
Forces the following command to appear on a new line.
Indents the following command output by one tab.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

4 of 50

Example:
$cat whoson
#!/bin/bash
date
echo Users Currently Logged In
who
$chmod u+x whoson
$whoson
Fri Jun 17 10:59:40 PDT 1994
Users Currently Logged In
alex
tty1
Jun 17 08:26
Jenny
tty02
Jun 17 10:04

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

5 of 50

The dot command


The dot command ( . ) is a built-in shell command that
lets you execute a program in the current shell and
prevents the shell from creating the child process.
There is a space between the dot command and its
argument.
$ . whoson
If your login shell is not set up to search for executable
files in the working directory, try command:
$ ./whoson
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

6 of 50

Shell Variables and Related Commands


Shell environment variables are used to customize the
environment in which the shell runs.
A copy of environment variables as passed to every
command that executes in the shell as its child.
Most of these variables are initialized when
/etc/profile executes at login time.
It is possible to customize these variables in users
~/.profile statrtup file, or the ~/.bashrc,
~/.bash_login, and ~/.bash_profile files.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

7 of 50

Some Important Writable Bash Environment Variables


BASH
Full pathname to bash.
CDPATH
Contains directory names that are searched.
EDITOR
Default editor.
ENV
Path to look for configuration files.
HISTFILE Pathname of the history file.
HOME
Name of the home directory.
PATH
Users search path.
PPID
Parents process ID.
PS1
Primary shell prompt on command line.
PS2
Secondary shell prompt.
PWD
Name of the currently working directory.
TERM
Type of users console terminal.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

8 of 50

$0
$1 - $9
$*
$@
$#
$$
$?
$!

Read-Only Bash Environment Variables


Name of program.
Values of command-line arguments.
Values of all command line arguments.
Values of all command line arguments; each argument
is argument individually quoted if $@ is enclosed in
quotes.
Total number of command-line arguments.
PID of current process.
Exit status of the most recent command.
PID of the most recent background process.

Commands set, declare or env without arguments


are used to see the list of values of the Bash environment
variables.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

9 of 50

The shift command - promotes each of the command


line arguments. The second $2 becomes the first $1 ....
Successive shift commands make additional arguments
available. There is no unshift command to bring back
arguments that are no longer available.
$cat demo_shift
echo arg1=$1
shift
echo arg1=$1

arg2=$2

arg3=$3

arg2=$2

arg3=$3

$demo_shift alice helen jenny


arg1=alice
arg2=helen
arg3=jenny
arg1=helen
arg2=jenny
arg3=

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

10 of 50

The set command. When you call set command with one
or more arguments, it sets the values of the command line
argument variables ($1 - $9) to its arguments.
The set command may be used to cause it to use the
standard output of another command as its arguments.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

11 of 50

$date
Fri Jun 17 23:04:09 PDT 1996
$cat dateset
set `date`
echo $*
echo Argument 1: $1
echo Argument 2: $2
echo Argument 4: $4
echo $2 $3, $6
$dataset
Fri Jun 17 23:04:09 PDT 1996
Argument 1: Fri
Argument 2: Jun
Argument 4: 23:04:13
Jun 17, 1996
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

12 of 50

Without any arguments, set displays a list of all variables


that are set. It displays user-created variables as well as
shell keyword variables.
The shell stores the PID number of the process that is
executing it in the $$ variable. The shell substitutes the
value of $$ before it forks a new process to run a
command. The example below demonstrates that the shell
creates a new shell process when it runs a shell script.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

13 of 50

$cat id1
echo $0 PID = $$
$echo $$
14137
$id1
id1 PID = 15253
$echo $$
14137
Number 14137 is the PID of the login shell, and 15253 is the
PID of the subshell.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

14 of 50

Shell stores the exit status of the last command in the $?


variable. Nonzero exit means that the command failed.
Exit status may be specified using an exit command,
followed by a number, to terminate the script.
$cat es
echo Hi!
exit 7
$es
Hi!
$echo $?
7
$echo $?
0

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

15 of 50

Example:
$ set One Two Three
$ echo $3 $2 $1
Three Two One
$ set `date`
$ echo $1 $2 $3
Wed Nov 29

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

16 of 50

Prompt characters
Domain name of the host
Time in 12 hours hh:mm:ss format
The date in weekday month date format
Host name up to the first dot
The shell name
Time in 24 hour hh:mm:ss format
User name of the current user
Version of the Bash shell
Current working directory

\H
\T
\d
\h
\s
\t
\u
\v
\w

Examples:
PS1=\w$
PS1=\ht

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

17 of 50

User-defined variables
Name of the variable may be any sequence of letters and
digits with letter as the first character.
When you assign a value to a variable, you must not
precede or follow the equal sign with a Space or Tab.
Bash does not require the type declaration but declare
and typeset commands can be used to declare variables
type.
All Bash variable is string by default, but can be declared
to be an integer.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

18 of 50

Use echo to display their values.


The shell substitutes the value of a variable when you
precede the name of the variable with a dollar sign ($).
$person=alex
$echo person
person

$echo $person
$person
$echo \$person
$person

$echo $person
alex
$echo $person
alex
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

19 of 50

Double quotations marks are used to assign or display a


value that contains Space or Tab to a variable.
$person=alex and jenny
$echo $person
alex and jenny
The special characters such as * and ? should also be
quoted.
$memo=alex*
$echo $memo
alex*

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

20 of 50

$echo $memo
alex.report alex.summary
$ls
alex.report
alex.summary
To remove the value of a variable, set it to null:
$person=
or use unset command:
$unset person

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

21 of 50

The readonly command is used to ensure that the


value of a variable cannot be changed. Assign a value to
a variable before you declare it to be readonly.
$readonly person
The readonly command without an argument, displays
a list of all user-created readonly variables.
In case of use of export command with a variable name
as an argument, the shell places the value of the variable
in the calling environment of child process.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

22 of 50

$cat test1
feline=lion
echo test1 1: $feline
subtest
echo test1 2: $feline
$cat subtest
echo subtest 1:$feline
feline=tiger
echo subtest 2:
$feline
$test1
test1 1: lion
subtest 1:
subtest 2: tiger
test1 2: lion
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

$cat test2
export feline
feline=lion
echo test2 1: $feline
subtest
echo test2 2: $feline
$test2
test2 1: lion
subtest 1: lion
subtest 2: tiger
test2 2: lion

23 of 50

The read command reads one line from the standard


input and assigns the line to one or more variables.
If you enter more words than read has variables, read
assigns one word to each variable, with all the left-over
words going to the last variable.
If input contains special characters, and you want them to
be just values of variables, use double quotes.
If you want the shell to use the special meanings of the
special characters, do not use quotation marks.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

24 of 50

Example:
$cat readx
echo Enter a command: \c
read command
$command
echo Thanks
$readx
Enter a command: who
alex
tty11
Jun 17 07:09
scott
tty7
Jun 17 08:23
Thanks

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

25 of 50

Example:
$cat
echo
read
echo
echo

readc
Enter something: \c
word1 word2
Word 1 is: $word1
Word 2 is: $word2

$readc
Enter something: Monty Pythons Flying
Circus
Word 1 is: Monty
Word 2 is: Pythons Flying Circus

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

26 of 50

When you enclose a command between two backquotes


(`), the shell replaces the command with the output of the
command (command substitution).
$cat dir
echo You are using the `pwd` directory.
$dir
You are using the /home/jenny directory.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

27 of 50

Control-Flow Commands
The control-flow commands alter the order of execution of
commands within a shell script.
if ... then
if test condition
then
commands
fi
The test condition is relational expression that might have
one out of two values: true or false.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

28 of 50

There are two different formats for the test expression:


test expression
[expression]
The expression contains one or more criteria evaluated
by test:
-a
separating two criteria is a logical AND operator,
-o
is a logical OR operator,
!
is NOT operator.
Operator -a takes precedence over -o.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

29 of 50

Operators for the test Command String Testing


string
True if string is not null string.
-n string
True if string has a length greater than zero.
-z string
True if string has length zero.
string1 = string2 True if string1 and string2 are the same.
string1 != string2 True if string1 and string2 are not the same.
Operators for the test Command Integer Testing
int1 relop int2
The relop is relational operator:
-gt greater than
-ge greater than or equal
-eq equal to
-ne not equal to
-le less than or equal to
-lt less than

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

30 of 50

-d file
-f file
-L file
-r file
-s file
-w file
-x file

Operators for the test Command File Testing


True if file exists and is directory.
True if file exists and is an ordinary file.
True if file exists and is a symbolic link.
True if file exists and you have read access permission.
True if file exists and contains information.
True if file exists and you have write access permission.
True if file exists and you have execute access permission.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

31 of 50

Example:
#!/bin/bash
echo Enter filename: \c
read filename
if [-r $filename -a -s $filename]
then
echo File $filename exists and is not empty.
echo You have read access permission to the file.
fi

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

32 of 50

if ... then ... else


if test-condition
then
commands
else
commands
fi
If the test-command returns a true value, if structure
executes the commands between then and else
statements and then passes control to fi, and the shell
continues with the next command in the script. If the testcommand returns a false status, it executes the
commands following the else statement.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

33 of 50

Example:
$cat AreYouOK
#!/bin/bash
echo Are you OK? #User prompt
echo input Y for yes and N for no:\c
read answer
if test $answer = Y
then
echo Glad to hear that.
else
echo Hope youll get better soon.
fi

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

34 of 50

if ... then ... elif


if test-statement
then
commands
elif test-command
then
commands
else
commands
fi

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

35 of 50

The elif statement combines else and if statements


and allows construction of a nested set of if ... then
... else structures.
Example:
#!/bin/bash
echo word 1: \c
read word1
echo word 2: \c
read word2
echo word 3: \c
read word3

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

36 of 50

if [$word1=$word2 -a $word2=$word3]
then
echo Match: words 1, 2 & 3
elif [$word1 = $word2]
then
echo Match: words 1 & 2
elif [$word1 = $word3]
then
echo Match: words 1 & 3
elif [$word2 = word3]
then
echo Match: words 2 & 3
else
echo No match
fi
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

37 of 50

Arithmetic Operations in BASH


The values are stored in Bash as strings. The Bourne
shell does not include a simple, built-in operator for
arithmetic and logic operations.
Example:
$x=20
$echo $x
20
$x=$x+1
$echo $x
20+1

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

38 of 50

The shell did not add number 1 to the value of x. It


concatenated the string +1 to the string value of x.
There are three ways to perform arithmetic on numeric
data in Bash:
o By using the let command,
o By using the shell expression $((expression)), and
o By using the expr command.
The expression evaluation is performed in long integers
and no overflow check is performed.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

39 of 50

The Bash let command is used to evaluate the


arithmetic expressions by specifying them as arguments.
let expression-list
If expression contains space characters it has to be
surrounded by double quotes.
$let x = 2 y = 3
$let z=x**y
$echo The values of z is $z
The value of z is 8

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

40 of 50

In
$((expression))
the value of expression is calculated and the result is
returned.
$x=2 y=3
$echo The value of z=x*y is $((x*y))
The value of z=x*y is 8
$let i=5
$let i=i+1
$echo $i
6

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

41 of 50

$x=3
$((x=x-2))
$echo $x
1
Command
expr args
provides arithmetic operations capability and evaluates
either numeric or nonnumeric character strings.
The expr command takes the arguments as
expressions, evaluates them, and displays the results on
the standard output device.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

42 of 50

Arguments may be arithmetic, relational, logical, and


string manipulation related expressions.
Example:
$expr 7 12
-5
$expr 2.5 1.2
expr: nonnumeric argument
Both Bourne Shell and BASH support only integer
arithmetic.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

43 of 50

Because the * (multiplication) and % (reminder)


characters have special meaning to the shell, they must
be preceded by a backslash (\) for the shell to ignore
their special meanings.
$expr 15/3
5
$expr 12\*3
36
$expr 10\%3
1
The expr utility returns exit status of 0 if the expression
is neither a null string nor the number 0, a status of 1 if
the expression is null or 0, and status of 2 if the
expression is invalid.
Sheridan College - Victor Ralevich
UNIX/LINUX BASH Programming 1

44 of 50

The single back quotations ( ` ) surrounding the


command cause the output of the command to expr to
be substituted.
$x=10
$x=`expr $x+2`
$echo $x
12
The expr command provides relational operators that
work on both numeric and nonnumeric arguments.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

45 of 50

If both arguments are numeric, the comparison is


numeric. If one or both arguments are nonnumeric, the
comparison is nonnumeric and uses the ASCII values.
The relational operators are: =, !=, <, <=, >, >=
The expr command displays 1 when the comparison is
true, and 0 when comparison is false.
Because the > (greater than) and < (less than) characters
have special meaning to the shell, they must be
proceeded by a backslash ( \ ) for the shell to ignore their
special meaning.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

46 of 50

Example:
$ expr 10\<20
1
$expr 10\>20
0
Variables can be declared as integers with the
declare i
command. If you attempt to assign any string value, Bash
assigns 0 to the variable.

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

47 of 50

Numbers can also be represented in different bases,


binary, octal, hex using expression:
variable=base#number
Examples:
$declare i x=017 #octal number
$echo $x
15
$x=2#101
$echo $x
5

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

48 of 50

$x=16#b
$echo $x
11
$ declare i num
$ num=hello
$ echo $num
0
$num=5+5
$echo $num
10

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

49 of 50

$num=4 * 5
$echo $num
20
$num=4*5
$echo $num
20
$num=4 * 5
$echo $num
bash: *: command not found

Sheridan College - Victor Ralevich


UNIX/LINUX BASH Programming 1

50 of 50