2

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.

0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

5 Comments

Good show. Had forgotten about :q and probably wouldn't have figured out that usage anyway. Good luck to all.
Thank you. It worked like a charm. I am familiar with bash but cshell is needed for a project. I'm still in shock by how counter intuitive it is.
@east.charm: Does "cshell is needed for a project" mean that it's a requirement for a homework assignment? Really, requiring csh makes sense only if the goal is to learn csh. (I used csh, and later tcsh, for many years; I finally switched to bash for both scripting and interactive use a few years ago.)
Not a school assignment. I'm interning in a company that uses it :(
@east.charm: My sympathies.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.