Вы находитесь на странице: 1из 47

Shell Scripting I

Ing. Ruben Cordova


Advanced Networks Research Lab.
Pontifical Catholic University of Peru

1
Outline

 Introduction
 Linux Kernel
 Linux Shell
 Shell scripting
 Compiled vs. interpreted
 Variables
 How to write and execute scripts
 Bash programming
 Shell arithmetic
 Command-line arguments
 Echo
 If sentences
 For loops
2
Introduction: Linux Kernel

 Part of GNU/Linux OS that manages resources


 I/O
 Process
 Device
 File
 Memory
 Decides who will use the resource, for how long and when
 Intermediary between computer hardware and program/application/shell

3
Introduction: Linux Kernel [1]

4
Introduction: Linux Shell

 Context
 Computers understand '0' and '1' (binary language)
 Early days: instructions provided in machine code (assembly language): 
 8B 03 34 12 <--> MOV CX, 1234H

 Shell
 Command-language interpreter 
 Accept commands in human language (English) and translate them to binary
language
 Read commands from input devices (keyboard) or files

5
Introduction: Linux Shell

6
Introduction: Shell examples

Shell Name Developed in Type of OS


BASH (Bourne-Again SHell) Free Software Foundation Linux
CSH (C Shell) University of California  BSD
KSH (Korn Shell) AT&T Bell Labs Unix
Command Prompt Microsoft MS-DOS
(cmd.exe)

*tmux
https://gist.github.com/MohamedAlaa/2961058
7
Introduction: Change shell per user

 Edit /etc/passwd file (root required)


 Test modifications:
 ssh localhost
 su {username}

8
Introduction: Linux Shell CLI

 Command Line Interface


 Provided by Shell to Linux systems
 Commands are typed in CLI using keyboard
 Prompt: 
 Sequence of one or more characters
 Indicates readiness to accept commands
 In Unix and derivate systems: ends with '$' or '%' (normal user) and '#' (superuser)

9
Activity 1: First steps with shell

a) Available shells in system


cat /etc/shells
b) Find out which shell we are using
echo $SHELL
c) How to use shell?
- Shell starts as soon as log into system
- Type commands

10
Introduction: Linux common
commands
 ls  cp
 cat  mv
 who  rm
 date  chmod
 pwd  whoami
 echo  wc
 more  grep
 tail  sort

11
Introduction: Process

 Program or task carried out by computer


 Perform some job
 When a process is started, it is assigned a process-id (PID)
 Maximum PID:
 System: check ‘/proc/sys/kernel/pid_max’
 Per user/group: configurable in ‘/etc/security/limits.conf’

12
Introduction: Why processes?

 Linux is multi-user, multitasking OS


 Can run more than 1 process simultaneously 

13
Introduction: Linux commands related
to Process
 ps: see current running process
 Option ‘T’ to see process status
 kill {PID}: stop process with process-id 'PID’
 Kill process in background: kill {job-id}
 &: used to run process in background
 ‘jobs’ command: list processes in background
 Resume process in foreground: fg {job-id}
 Resume process in background: bg {job-id}
 Suspend/stop process: Ctrl + Z (send to background)
 Terminate process: Ctrl + C
14
Introduction: Redirection

 Most commands gives output on screen or take input from keyboard


 In Linux it is possible to send output to file and read input from file
 '>': output of Linux command to a file
 '>>': output of Linux command to the end of a file
 '<': take file as input of Linux command
 <<<: take string as input of command
 Solution to execution of commands using pipe (second command in subshell,
variables won’t pass to parent shell)

15
Activity 2: Use redirection

a) Redirect output of 'ls -lh' to file 'temp.txt'


b) Redirect output of 'date' to the end of file 'temp.txt'
c) Redirect content 'of temp.txt' as input of 'cat'

16
Activity 2: Solutions

a) 'ls -lh' > 'temp.txt'


b) 'date' >> 'temp.txt'
c) cat < 'temp.txt'

17
Introduction: Pipe

 Connects output of one programs to the input of another program without


temporary file
 Used to run multiple commands from same command-line
 Syntax: command1 | command 2

18
Activity 3: use pipe

a) See how many users are logged in


b) Find out how many files/directories (in home directory) start with 'Do' string

19
Activity 3: use pipe

a) who | wc –l
b) cd ~
ls -lh | grep "Do"

20
Shell Scripting 

 Series of Linux commands


 Can take input from user or file and output them on screen
 Allows to create own commands:
 Automate every-day tasks
 Save time 

21
Shell Scripting: Interpreted vs.
Compiled language

Interpreted Compiled
 Instructions are not translated to  Instructions translated to machine
machine language, but to language (executed directly by
intermediate language processed hardware)
by interpreter (program)  Advantage
 Advantage  Faster than interpreted: machine
 Portability code

SHELL SCRIPTING (COMMAND LANGUAGE) IS INTERPRETED (BY SHELL, i.e. bash)


22
Shell Scripting: Variables in Linux

 To process data, sometimes it need to be kept in RAM


 Unique name to identify memory/location address (holds data)
 Named-storage location
 Can take different values, but only one at a time
 Types:
 System variables: created and maintained by Linux (capital letters)
 User defined variables (UDV): created and maintained by user (lower case)
 Print using program 'echo' and '$' followed by variable name*
 Use value in variable:
 echo $HOME (output: /home/labtel)
cd $HOME/Downloads (same as cd /home/labtel/Downloads)
23
Activity 4: print values of system
variables
 SHELL
 BASH
 BASH_VERSION
 HOME
 LOGNAME
 PWD

24
Shell Scripting: Define UDV

 Syntax: variable_name=value
 Example: temp_var=10
 Rules:
 Must begin with alphanumeric or underscore character
 Do not put spaces (either side of equal sign) when assigning value to variable
 Variables are case-sensitive
 NULL variable: has no value at time of definition

25
Shell Scripting: Access value of UDV

 'echo' command
 -n: do not output the trailing new line
 -e: enable interpretation of backslashes escapes
 Shell arithmetic:  use 'expr' command
 Space required between operator and numbers
 Assign result to variable: z=`expr x + y`
 'read' statement: get input from keyboard and store it in variable

26
Shell Scripting: Additional options

 Quotes:
 Double quotes: remove meaning of characters
 Single quotes: enclosed remains unchanged
 Back quotes: execute command
 Comments start with '#'

27
Shell Scripting: Write and execute
scripts
 Use text editor (emacs, vi/vim, nano, cat)
 See line numbers: nano –c, vim (:set nu)
 Set execute permissions to user (creator is not allowed by default)
 Execute using ./{script_name} (dot indicates execute command in current
shell) or specifying shell to use
 System variable PATH: script as command

28
Bash Scripting: Shell Arithmetic

 Addition: +
 Subtraction: -
 Multiplication: \*
 Division: /
 Remain: %

29
Bash Scripting: Arguments

 Arguments can be passed to script: {script} arg1 arg2 …


 Each script argument can be referenced in the script by a '$' followed by the
order they were passed
 '$0': script executed
 '$#': number of arguments
 '$*': arguments of script

30
Activity 5: write and execute first
script
 Create a script that clears the terminal screen and prints 'Welcome to v305!'.
Use comments to describe what script does
 Create a script that receives two numbers as arguments, sum them and print
the sum
 Create a command from this script 

31
Activity 5: Solutions

 clear
echo "Welcome to v305!“
 addition.sh
echo –n “1st number: ”
read num1
echo –n “2nd number: ”
read num2
echo `expr $num1 + $num2`
 Verify that ‘$HOME/bin’ is in PATH system variable
cd ~
mkdir bin
mv ../addition.sh /bin

32
Bash Scripting: Exit status

 When particular command is executed in Linux, it returns two types of


values: 
 Zero value: successful command
 Nonzero value: not successful or error executing script/command
 Check value using 'echo $?’
 Exit status meaning
http://tldp.org/LDP/abs/html/exitcodes.html

33
Bash Scripting: Comparison expression

 Good practice: quote variables when evaluating their content


 Mathematical comparison
 >(=): greater (or equal) than
 ==: equal to
 !=: not equal to
 <(=): less (or equal) than

34
Bash Scripting: Comparison expression

 String comparison
 string1 = string2: equal
 string1 != string2: not equal
 String evaluation
 String1: not null or defined
 -n string1: not null and does exist (variable MUST be quoted)
 -z string1: null and does exist

35
Bash Scripting: examples

 Mathematical comparison:

((“$1” <= “$2”))

 String comparison:

[ -n “$var” ]

36
Bash Scripting: Comparison expression

 Mathematical expression
 -eq: equal to
 -ne: not equal to
 -lt: less than
 -le: less than or equal
 -gt: greater than
 -ge: greater than or equal
 Example: are arguments equal?
[ “$1” –ne “$2” ]

37
Bash Scripting: ‘test’ command

 Can be used to evaluate integers


 File and directory
 -e file: file exists
 -s file: non empty file
 -f file: file exist or normal file and not a directory
 -d dir: directory exist and not a file
 -w file: writeable file
 -r file: read-only file
 -x file: file is executable

38
Bash Scripting: ‘test’ command
examples
 Arithmetic: number comparison
test “$1” -lt “$2”

 Files and directories: test existence of file


test –e “$1”

39
Bash Scripting: Logical operators

 '!': logical not


 '-a': logical AND
 '-o' logical OR

40
Bash Scripting: Logical operators
example
 Order of inputs

[ “$1” –lt “$2” –a “$2” –lt “$3” ]

 Greater argument

test ! “$1” –gt “$2”

41
Bash Scripting: Decision making

 If condition is true, then execute given command


 Optional ‘elif’ (previous condition not true) and ‘else’ (any of previous
conditions true) sentences
 Syntax:
if {condition}
then
    command if condition is true or exit status of condition is zero
elif {condition1}
then
    command1 if condition1 is true or exit status of condition is zero
else
    commandN if none of above conditions are true
fi
42
Bash Scripting: Decision making
example
 Show whether input number is 1-digit, 2-digit or more. Validate is greater or equal than zero

echo "Type an integer number greater than 0“


read num

if [ "$num" -le 0 ]
then
echo "Number is not greater than 0“
elif [ "$num" -lt 10 ]
then
echo "1 digit number“
elif [ "$num" -lt 100 ]
then
echo "2 digit number“
else
echo "Number with 3 or more digits“
fi
43
Bash Scripting: Loops

 Repeat particular instruction(s) until condition is satisfied


 Two types:
 For
 While
 Control loops:
 break: terminate execution of loop
 continue: exit current execution (continue loop)
 Nested loops:
 Exit nested loops: break/continue [level]

44
Bash Scripting: For loop

 'for' syntax
for {variable_name} in {list}
do
    execute one of each item in list until end
done
 “for” statement can use following syntax
for (( expr1; expr2; expr3 ))

45
Activity 6:

 Script to print first ten even numbers


 Script to make a division using addition and subtraction. Also, indicate remain

46
References

1. Vivek G. Gite. Linux Shell Scripting Tutorial


http://www.freeos.com/guides/lsst/index.html
2. Mendel Cooper. Advanced Bash-Scripting Guide
http://tldp.org/LDP/abs/html/index.html

47

Вам также может понравиться