Sunteți pe pagina 1din 40

Introduction

UNIX System Programming

Shashwat Shriparv
dwivedishashwat@gmail.com
InfinitySoft 1
User UNIX Interface: SHELL
Provides command line as an interface between the user and
the system
Is simply a program that starts automatically when you login
Uses a command language
Allows programming (shell scripting) within the shell
environment
 Uses variables, loops, conditionals, etc.

Accepts commands and often makes system calls to carry


them out

2
Shell Variables
A shell variable is a keyword that is set by the shell for a
specific use.
Usually entered in all uppercase letters.
To display the contents of an individual variable, use the
echo command and place a dollar sign before the variable
name.
Example: echo $BASH

3
Various UNIX shells
sh (Bourne shell)
ksh (Korn shell)
csh (C shell)
tcsh
bash
Differences mostly in scripting details

4
Predefined Shell Variables
Shell Variable Description
PWD The most recent current working directory.
OLDPWD The previous working directory.
BASH The full path name used of the bash shell.
RANDOM Generates a random integer between 0 and 32,767.
HOSTNAME The current hostname of the system.
IFS Internal Field Separator used as a separator between
words in the shell or shell scripts.
PATH A list of directories to search of commands.
HOME The home directory of the current user.
PS1 The primary prompt.
PS2 Second level prompt.
5
Simple Redirections
Command Syntax Short Description

cmd > file Send output of cmd to file

cmd >> file Append output of cmd to file

cmd < file Take input from file

cmd << text Read stdin up to a line identical to


text a.k.a “here command”

6
Wildcards
Allows you to select files that satisfy a particular name
pattern (wildcards)
Character Description Example
* Match zero or more char. ls *.c
? Match any single character ls conf.?
[list] Match any character in list Ls [kdgp]*
[lower-upper] Match any character in range Ls [c-fmrv-z]*

7
Command Substitution
Command substitution allows you to substitute the output of a
command in place of the command itself.
Two forms of command substitution:
$(command)
`command`
Examples:
$ echo "User" $(whoami) " is on the system " $(hostname)
User krush is on the system ux
$ echo "Today's date is" `date`
Today's date is Sun Jul 17 08:06:28 CDT 2005

8
Shell Variables
Named locations to store data
Their values can be obtained by preceding their names with
dollar signs ($)
Environment variables are conventionally named in all capital
letters and their values can be made known (export) to
subprocesses.

9
User-defined Shell Variables
Created by a user/programmer to store information to be used
in a current script (i.e. not to be used by other scripts called
by the current script)
Unless exported, they are available only (locally) to the shell
in which they are created
The variable names consist of lowercase letters

10
User-defined Shell Variables
Syntax: variable_name = value
Example: Create a variable named “rate” to hold an interest
rate and initialize it to 7.65.
$ rate=7.65

Note that you should use double quotes if the value of a


variable contains white spaces.
Example: name=“Thomas William Flowers”

11
Accessing Shell Variables
To access the contents a shell variable, simply place a dollar
sign ($) in front of the variable name
Syntax: $variable_name
Example: Display the contents of the variables named
MYPATH and “rate”, which were defined previously.

$ echo $MYPATH
/home/ux/krush/bin
$ echo $rate
6.75

12
Resetting Variables
To reset or remove the contents of defined variables, use the
command “unset”
The unset command can be used to unset both local and
environment variables
Syntax: unset variable_name
Example: Remove the contents of the variable MYPATH.

$ unset MYPATH
$ echo $MYPATH

$ Null value
displayed
13
Listing Variables
Use the commands: env and set
env – list all shell variables (including exported)
set – list all set variables: local, and exported (including
variables set to null)

14
User input
allows to prompt for user input
Syntax:

read var-name [more vars]

or

read –p “prompt” var-name [more vars]

words entered by user are assigned to


var-name and “more vars”
last variable gets rest of input line
15
Command-line Arguments
Use command-line arguments (positional parameters)
to pass information into shell script.
Parameter Meaning
$0 References the name of the current shell script or a UNIX
command
$1-$9 Positional parameters 1 through 9
$# The number of positional parameters
$* All positional parameters
$@ All positional parameters

16
Examples:
$ set tim bill ann fred The ‘set’
$1 $2 $3 $4 command can
$ echo $* be used to
tim bill ann fred assign values to
$ echo $# positional
parameters
4
$ echo $1
tim
$ echo $3 $4
ann fred

17
Decision Structure
To briefly discuss the following topics:
Decision-structure theory
Relational operators
If-statement
If-elif-statement
Case-statement
Logical operators
File testing

18
Decisions

19
The if…statement
The if construct has the following syntax:
if [ condition ]; then
statements
[elif condition
then statement]
[else
statements]
fi
The simplest form without the elif and else parts executes
the statements only if the condition is true.
The phrase elif stands for “else if.” It is part of the if
statement and cannot be used by itself.

20
Relational Operators
Meaning Numeric String
Greater than -gt
Greater than or equal -ge
Less than -lt
Less than or equal -le
Equal -eg =
Not equal -ne !=
str1 is less than str2 str1 < str2
str1 is greater str2 str1 > str2
String length is greater than zero -n str
String length is zero -z str
22
Logical Operators
To test multiple commands and conditional expressions, you
can implement the following operators:
AND (&&)
OR (||)
NOT (!)

23
Logical Operator: &&
The “AND” logical operator has the following syntax:

statement1 && statement2

This means: “Execute statement1, and if its exit status is 0


(succeed), execute statement2.”
If statement1 returns a non-zero exit status, then
statement2 does not run.

24
Logical Operator: ||
The “AND” logical operator has the following syntax:

statement1 || statement2

This means: “Execute statement1, and if its exit status is


non-zero (fail), execute statement2.”
If statement1 returns 0, then statement2 does not run.

25
Example: File Testing
#!/bin/bash
echo "Enter a filename: "
read filename
if [ ! –r “$filename” ]
then
echo “File is not read-able”
exit 1
fi

26
The case Structure
Syntax: Purpose:
case test-string in To implement
multi-way branching
pattern1) command-list1
;;
pattern2) command-list2
;;
patternN) command-listN
;;
esac

27
The while Loop
Purpose:
To execute commands in “command-list” as long as
“expression” evaluates to true

Syntax:
while [ expression ]
do
command-list
done

28
The until Loop
Purpose:
To execute commands in “command-list” as long as
“expression” evaluates to false

Syntax:
until [ expression ]
do
command-list
done
29
The break command
while condition
do
cmd-1
This iteration is over
break and there are no more
cmd-n iterations
done
echo “done”

30
The continue command
while [ condition ]
do
cmd-1
This iteration is over;
continue do the next iteration
cmd-n
done
echo “done”

31
The for Loop
Purpose: To execute commands in “cmd-list” as many
times as the number of words in the “argument-list”

Syntax:
for variable in argument-list
do
cmd-list
done

32
Example1: The for Loop
$ cat for.demo $ for.demo
#!/bin/bash 2
for i in 7 9 2 3 4 5 3
do 4
echo $i 5
done | sort -n 7
9

33
Shell Functions
To briefly discuss the following topics:
Understand functions
Components of functions
Implement functions
Why should we write shell functions?
It’s fast. When you invoke a function, it is already in the
shell’s memory.
Easy to develop, organize and maintain long source code.

34
Shell Functions
A function is a set of statements that can be used to
perform a specific task.
Functions are self-contained blocks of code that can be
used multiple times simply by referencing the function
name.
Functions can accept values and return a result.

35
Shell Functions
Functions are implemented within a shell script and they
are usually placed at the beginning of the script.
They must be defined before they can be referenced.
General format:
function function-name ( )
{
statements
[return]
}

36
Shell Functions
You can place commands before the function as long as
they do not reference the function.
When the shell interprets a script, it reads past the
function and executes statements following it.
Once the function is called, the shell executes the
statements within the function.
After the function is completed, the shell returns control
to the statements following the function call.

37
Example: function
#!/bin/bash

funky () {
# This is about as simple as functions get.
echo "This is a funky function."
echo "Now exiting funky function."
}

# Function declaration must precede call.

funky

38
Example: function
#! /bin/bash

if [ "$USER" = bozo ]
then
bozo_greet ()
{
echo "Hello, Bozo."
}
fi

bozo_greet
39
Example: function
#! /bin/bash

bozo_greet ()
{
echo "Hello, $1."
}

bozo_greet bozo
bozo_greet $USER

40
THANK YOU

Shashwat Shriparv
dwivedishashwat@gmail.com
InfinitySoft 41

S-ar putea să vă placă și