Shell Script

Download Report

Transcript Shell Script

#!/bin/sh
Jaeho Shin
<[email protected]>
What is a “Shell”?
• Interface between user and the
operating system
Shell
• sh, bash, csh,
tcsh, ksh, …
user
user
OS
user
Shell Script?
• A command programming language
that executes commands read from a
terminal or a file
• Uses built-in commands/syntax and OS
programs
• Why use shell scripts?
– Can do repetitive tasks easily & quickly
Basic Syntax
•
•
•
•
•
•
# comments…
list; list; list; …
list | list | list …
list && list || list …
list < input > output
list &
•
•
•
•
•
•
•
(list)
`list`
{ list;}
name=value
name () { list;}
$name
${name}
Flow control - if
• if list ; then list ;
[ elif list ; then list ; ]
[ else list ; ]
#!/bin/sh
fi
myvar="myvalue"
if [ "$myvar" = "" ]; then
echo "nothing!";
else
echo "you’ve got $myvar"
fi
Flow control - for
• for name [ in word … ]
do list done
#!/bin/sh
for i in 5 4 3 2 1;
do echo "countdown: $i";
done
Flow control – while
• while list;
do list;
#!/bin/sh
done
unit="x"
while [ "$string" != "xxxxxx" ]; do
string=$string$unit;
echo "not yet~ ($string)";
done
echo "ok~ got $string"
Flow control - case
• case word in
[ pattern [ | pattern ] ) list ;; ] … esac
#!/bin/sh
case $1 in
hi) echo "hello~";;
bye) echo "byebye~";;
esac
Predefined variables
•
•
•
•
# : number of arguments
? : last command’s return value
$ : process id of this shell
! : process id of last background
command
• 1, 2, 3, … 9 : n-th argument
Example script
#!/bin/sh
# shortcut script
case $1 in
a) telnet ara;;
s) telnet ska;;
l) telnet loco;;
n) telnet noah;;
m) mutt
t) if [ -f $HOME/TODO ]; then
cat $HOME/TODO | more;
fi;;
esac
Pipelining
• Syntax : command1 | command2
• Connecting one process(command1)’s output
to another process(command2)’s input
• Can do complex jobs by combining many
small programs
• Examples
– ls -l | sort
– finger | cut -d " " -f 3,4,5 | wc
Redirection
• Syntax : command <|<<|>|>> path
• Connecting process’s output/input to a given
file
• Can save any output to a file and can load
any file to a program input
• Examples
–
–
–
–
du -sh * > du_dump.file
find ~ -name .*rc > rcfiles
sort < unsorteddata > sorteddata
date >> mydatelogfile
Job control
• Job control is a way to do multitasking
with the command-line interface
• Syntax and commands
– command &
– bg [%n]
– fg [%n]
– jobs
– kill [%n]
References
• man pages for sh/ksh/bash/csh/tcsh