Shell Programming
With regard to yesterday's blog,
you may want to put that in a script so that you do not have to re-type commands all the time.
So you first cut may be like this:
egrep '^ch' /etc/passwd | cut -f7 -d: | grep -c /bin/ksh
However, this script is not very flexible. First you did not tell the script what shell you want to run with. Second, you assume user has all the search path to be the same as your environment. Thirdly, you have the search string hard coded. OK, lots of room for improvement. Let's give this script a make-over then, we call this script "fshell.sh:
#! /bin/sh if [ $# -ne 2 ]; then echo "Usage: $0 &lgt;pattern> <shell>" exit 1 fi pattern=$1 shell=$2 # set up search path PATH=/usr/bin export PATH egrep "^$pattern" /etc/passwd | cut -f7 -d: | grep -c "$shell"
Now you have a very generic script that can handle different pattern and shell. Let run it:
$ ./fshell.sh Usage: ./a.sh <pattern> <shell> $ ./fshell.sh ch /bin/ksh 4 $ ./fshell.sh ch /bin/sh 1Let me provide you with some explanation. Line 1: Tell the system that this script (fshell.sh) is written in Bourne Shell (/bin/sh) syntax Line 3-8: Check if you supply with 2 arguments, namely the pattern and shell. If not, exit with status 1, else set the variables pattern and shell accordingly Line 10-11: Set up the search path environment variable. We do not want to use user's search path Line 13: The commands, this return the number of match.
Not too difficult to digest, isn't it. Next time when you want to write a simple script, do follow this approach.
Labels: shell script, unix
0 Comments:
Post a Comment
<< Home