A short set of neat shellscript examples

Written by Ian on 26/08/09


In UNIX-based systems, pipes (|) and redirections (< or >) are useful:



















echo helloprints hello to the screen
echo hello > hello.txt creates a file hello.txt containing hello
echo " world" >> hello.txt now the file contains hello world
cat /var/log/syslog displays the system log file
cat /var/log/syslog | head displays the first 10 lines of the syslog
head /var/log/syslog does the same
cat /var/log/syslog > temp copies the syslog to a file called temp
cp /var/log/syslog temp does the same
tail -5 temp displays the last 5 lines of file temp
echo hello | myprog runs myprog, puts 'hello' on stdin
cat temp | myprog runs myprog with content of file temp on stdin
myprog < temp runs myprog with content of file temp on stdin
myprog 2> errlog runs myprog, stderr output redirected to file errorlog
myprog < temp 2> errlog combines the previous two examples
OK now here are two more complicated examples for homework try these out:
myprog < temp <2 erin 2> errlog | myprog2 >> mylog
ls -l | grep 2006 | wc -l

















Conditional statements are also provided:
if test -f tcp_log; then check if the file specified exists

echo "TCP server is running"

elif test -e /usr/bin/tcp_server; then

/usr/bin/tcp_server '&';

run a program, '&' means in the background

else

echo "TCP server not found"

fi




















Loops are very well catered for in the shell:

for sourcecode in *.c; do

echo "Found one " $sourcecode

done

for name in *

do

case "$name" in

*.c ) echo "$name is a C source file" ;;

*.ps ) echo "$name is a postscript file" ;;

*.txt ) echo "$name is a text file" ;;

esac

done


I'll write some more next time, about grep, sed and awk!