Help with strings in Bourne shell

Kenneth Almquist ka at june.cs.washington.edu
Sun Apr 30 06:02:33 AEST 1989


rudolf at oce.orst.edu (Jim Rudolf) writes:
> If I have a Bourne script called 'foo' and I call it with the arguments:
>    foo "color = red" "size = big"
> then from within foo they will be read as:
>    $1 = "color = red"
>    $2 = "size = big"
> However, I want to read from stdin (or maybe a redirected pipe), and I
> can't get it to work no matter what strange combination of quotes I use!
> I would like to do something like:
>    read args
>    for i in $args
>    .
>    .
> so I can process each string in turn.  Why can't I get this to work?
> Do command line arguments get treated differently than arguments read
> from within the script?  Any suggestions would be greatly appreciated.

Presumably you want to read in a single line with multiple quoted strings
in it.  The read command doesn't handle quoted strings.  (The shell manual
page lies.)  One possible solution is to use the eval command:

	read line || exit 0	# exit if end of file
	eval "set $line"	# parse line
	for i in "$@"
	...

Let's work through an example.  Assume that the input line is

	"color = red" "size = big"

Then the read command will store the line in the variable "line".  The
second command will run the eval command with a single argument, the
string

	set "color = red" "size = big"

The set command assigns its arguments to the positional parameters, so
you will get

	$1 = "color = red"
	$2 = "size = big"

The for loop will then step through the positional parameters.

Several warnings about this.  First, if the first argument to set begins
with a minus or plus sign, it will be interpreted as an option.  Second,
this won't work if the number of arguments to set is zero.  Third, the
set command changes the positional parameters, making the original arguments
to the shell procedure inaccessible.  And fourth, if the argument to "set"
is not syntactically correct, the shell procedure will terminate.
				Kenneth Almquist



More information about the Comp.unix.questions mailing list