String extraction from user input - sh

Hi,

I have a shell script to build components of a product. The follow snippet will explain what I am doing.

# !/bin/sh
for choice in "$@" ;
do
case $choice in
"o") echo "Calling $choice" ; o ;;
"i") echo "Calling $choice" ; i ;;
"w") echo "Calling $choice" ; w ;;
"m") echo "Calling $choice" ; m ;;
"all") o ; i ; w ; m ; ftp ;;
*) usage ;;
esac
done

Now when I call the script I call it in the following manner: sh build.sh i o w m

What I plan to do is take the input as a single argument containing the required components; sh build.sh iowm

Is there anyway to extract the individual charaters from the input string. And then check for i/w/o/m and then carry on with the build.

Also is there a way to check for 0 arguments using $@ . Currently I use
if test $# = 0

Thanks in advance,
Vino

What system are you using? Post the output of "uname -a".

Linux staci21 2.4.21-27.ELsmp #1 SMP Wed Dec 1 21:59:02 EST 2004 i686 i686 i386 GNU/Linux

That makes a big difference. Your /bin/sh is actually bash rather than the old bourne shell. Try something like:

#! /bin/sh

parm=$1

while ((${#parm})) ; do
        rest=${parm#?}
        char1=${parm%$rest}
        parm=$rest
        echo $char1 $parm
done
exit 0

But I have set the sh to /bin/sh. Does it still make a difference ???

No, it shouldn't matter - most Linux systems have /bin/sh linked to /bin/bash - to check, do

ls -li /bin/sh /bin/bash

see if a) the inode numbers are the same or b) there's a soft link.

Cheers
ZB

Perderabo,

Thanks for the solution. That extracts the first character. Is there anyway I can search for a character in the input string. For eg. if the input string is iowm, I need to search for the character o in the string. Something like grep on a charatcer string rather than a file.

Vino

Got it.

Solution is
if echo "$word" | grep q "$letter_sequence"

It was there in the Advanced Bash scripting guide. It can be found at http://www.tldp.org/LDP/abs/abs-guide.pdf

Thanks Perderabo
Thanks zazzybob.

Vino

That is not a great solution. It doesn't make sense to invoke an external program to do what bash can do internally...

if [[ $var = *k* ]] ; then echo yes ; fi

will test var for the presence of a "k".