Answers to examples
Note that these script begin with a line saying #!/bin/sh
.
This will force the script to be interpreted by the Posix
shell even if the user is using another, incompatible, type of shell.
Your system might require a different initial line. If you leave the
line out, the user's current shell will be used.
- Arguments
#!/bin/sh if [ $# = 1 ] then string="It is " ending="" else string="They are " ending="s" fi echo This $0 command has $# argument${ending}. if [ $# != 0 ] then echo $string $* fi
- Adding Numbers
#!/bin/sh echo "input a number" read number1 echo "now input another number" read number2 let answer=$number1+$number2 echo "$number1 + $number2 = $answer"
- Login Counting Script
#!/bin/sh times=$(who | grep $1 | wc -l) echo "$1 is logged on $times times."
- List Directories
#!/bin/sh for file in $* do if [ -d $file ] then ls $file fi done
- See Script
#!/bin/sh for file in $* do if [ -d $file ] then echo "using ls" ls $file else more $file fi done
- Word-length script
#!/bin/sh echo "Type a word" read word echo $word is $(echo -n $word | wc -c) letters long echo or $word is ${#word} letters long
- Safe Copying
#!/bin/sh if [ -f $2 ] then echo "$2 exists. Do you want to overwrite it? (y/n)" read yn if [ $yn = "N" -o $yn = "n" ] then exit 0 fi fi cp $1 $2
- Mailmerge
#!/bin/sh for name in $(<names) do sed s/NAME/$name/ <template >letter # here you could print the letter file out done