views:

1759

answers:

1

I have a script where the user should be able to enter a string with spaces. So far I have:

#bin/csh

echo "TEST 1"
echo -n "Input : "
set TEST = $<

echo "Var | " $TEST

set TEST=`echo $TEST`

echo "Var after echo | " $TEST

set TEST=`echo $TEST | sed 's/ /_/g'`

echo "Var after change | " $TEST

If I enter the string "r r r" at "input", $TEST would only take "r". I want to be able to set $TEST to "r r r". Is this possible? If I enter a string like "1 1 1" I get an error:

set: Variable name must begin with a letter.

What's the reason for this?

+3  A: 

It's because you're not using quotes in your SET statement. When you enter "r r r" as your input, the two different variants (unquoted and quoted) are equivalent to:

set TEST=$<    :is equivalent to:  set TEST=r r r
set TEST="$<"  :is equivalent to:  set TEST="r r r"

The first of those simply sets TEST to "r" and r to "" (twice!). The second sets TEST to "r r r". That's because csh lets you do multiple assignments like:

set a=1 b=2 c d=4

So you need to use the quoted variant of SET. Examine the following transcript to see how it works:

[pax ~]$ set x=$< ; echo .$x.
hello
.hello.

[pax ~]$ set x="$<" ; echo $x ; echo .$b.$c.
a b c
.a b c.
b: Undefined variable.

[pax ~]$ set x=$< ; echo $x ; echo .$b.$c.
a b c
.a.
...

[pax ~]$ set x=$< ; echo $x ; echo .$b.$c.
a b=7 c=urk!
.a.
.7.urk!.

The reason you're getting the error you describe with input of "1 1 1" is because you're effectively executing:

set TEST=1 1 1

and csh is taking this to mean that you want to create the variable TEST set to "1" followed by the variable 1, which doesn't start with a letter, hence not allowed. With the quoted variant, this becomes:

set TEST="1 1 1"

which will do what you expect.

paxdiablo
That worked. Thanks
Gayan