I have a command in my csh script that can give at least 2 lines of output but may be more. I am turning these lines into separate variables that I then want to pass to another command. How do I set my second command to loop through and run for each variable outputted from command 1? Below is my what I have that turns the output of command 1 into variables.

set vars = `echo "command 1"`

set numRows = $#vars  
if ($numRows < 2) then  
        echo "ERROR! $numRows rows!"  

`echo '/command2 -L '$vars[1]'`
  • That code you provided doesn't work - syntax error about the if statement. Also, even in the horror story that is csh, command substitution doesn't work as you've suggested. Perhaps you could provide the working code you do have?
    – Mike Diehn
    Dec 16, 2016 at 14:59

1 Answer 1


Note, I'm using bash, not csh, because I don't hate myself. But you can do all this in csh, you'd just have to translate. If you want to work in bash instead, simply run "bash --login" first and then you're working in bash.

To do the sort of task you describe in a shell script, we use pipes and not loops like you would in a programming language. Don't get me wrong, there are looping structures in csh and bash, but for what you've described, we do it differently.

If I had a command that produces multiple lines of output and I wanted those lines to be acted on one at a time by another command, I'd connect the two commands with a pipe | , like this maybe:

cat file.txt | grep "some words"

The grep command processes each line coming in from STDIN, which is linked by the pipe to STDOUT of the cat command. This is a trivial example, but it serves.


echo 'one,two,three' | tr ',' '\n'

That will replace all the commas with newlines, creating a three line output from the one line input.

If I wanted to add an extension to the names of all files in a directory, I might do something like this:

cd directory
for filename in *
  mv ${filename} ${filename}.extension

The * is file globbing pattern. File globbing is when a pattern on the command line is replaced with any filename in the current directory that matches the globbing pattern. The * means "anything"

  • 1
    Thanks Mike, thats done the trick. Im not using csh out of choice but i was restricted in what i could use. Ill avoid as much as i can in future though.
    – a.smith
    Dec 20, 2016 at 10:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.