Arguments and a bit about Functions… two nonintuitive words

February 10, 2007

Those of us who are used to command-line utilities, are used to passing arguments (aka parameters) to them: we don’t just run “ls“, we run “ls -ltSr“. So, how do we write a shell script which can take arguments?

There are two methods, and I will just deal with the simple approach, today. I’ll leave getopts for another day, when I have a little more time. The simple answer, is that, if we get called as “uppercase hello”, and we need to reply with “HeLlO”, then the script would look like this:

#!/bin/sh
# uppercase ... convert alternate words to uppercase
# note: there are many ways to do this (see previous posts) 
echo $1 | tr '[a-z]' '[A-Z]'
echo $2
echo $3 | tr '[a-z]' '[A-Z]'
echo $4
echo $5 | tr '[a-z]' '[A-Z]'
echo $6

If we say uppercase a b c d e f,then it will reply with AbCdEf. Still, not much fun.

We can rewrite it like this, using the shift command, which discards the $1 and promotes $2:

#!/bin/sh
echo $1 | tr '[a-z]' '[A-Z]'
shift

echo $1
shift

echo $1 | tr '[a-z]' '[A-Z]'
shift

echo $1
shift

echo $1 | tr '[a-z]' '[A-Z]'
shift

echo $1
shift

That way, we’re always dealing with $1. Otherwise, it’s just the same.

We can then put upper() into a function:

#!/bin/sh

upper()
{
echo $1 | tr '[a-z]' '[A-Z]'
}

for i in $*
do
        upper $1
        shift
        echo $1
        shift
done

This way, “$1″ is always the current argument. So “toupper.sh a b c d e f” will output “AbCdEf“.


Follow

Get every new post delivered to your Inbox.