cshell cannot set array of strings with spaces

4.4k views Asked by At

I am new to c shell. I've been trying to define an array of commands then run them using a loop but it keeps parsing the commands word by word instead of command by command.

The code is :

#!/bin/csh


set commands=("./cmd option1 option2" \
"./cmd option1 option2" \
"./cmd option1 option2" \
"./cmd option1 option2" \
)
foreach  c ($commands)

        echo $c
        $c
end
#EOF

The output is :

./cmd 
Output 
option1
command not found
option2
command not found

I think the error is in the loop, but I couldn't fix it.

1

There are 1 answers

5
Keith Thompson On BEST ANSWER

Change $command to $command:q.

For example:

% cat foo.csh
#!/bin/csh -f

set arr = ( 'zero one' 'two three' )
foreach elem ($arr:q)
    echo $elem:q
end
% ./foo.csh
zero one
two three
% 

This is one case where the :q suffix works and enclosing the variable reference in double quotes does not.

Note that I've added -f to the #! line. This tells csh not to load your startup files, which makes your script slightly faster and, more important, avoids unintentional dependencies on your own environment. csh or tcsh scripts should (almost) always have a -f on the #! line. (This does not apply to sh, ksh, bash, or zsh scripts; for those shells, -f has a different meaning.)

I am new to c shell

Perfect! That means this is a great time to switch to a shell that's more programmer-friendly, like bash or even sh.

bash supports arrays, though the syntax is a bit less convenient than csh's -- but bash's behavior is more consistent. One example: I'm not sure that I could prove from csh's and/or tcsh's manual that :q would work in this case; I had to use trial and error. I've used csh for many years, and I frequently run into this kind of thing.

Read this: http://www.perl.com/doc/FMTEYEWTK/versus/csh.whynot