0

I'm trying to convert a cshell script into a bash one. To compile some files in different subdirectories, it uses foreach

 cd $BLDSRCDIR
 foreach file ( $flist )
    $myCC -c $myCFLAGS $file.c -o $BLDDIR/$file.o
 end for

Because bash doesn't have foreach, I tried:

 for file [ $flist ] in
 do
    $myCC -c $myCFLAGS $file.c -o $BLDDIR/$file.o
 done

But this syntax is not correct ( syntax error near unexpected token [' ). There is probably more than one solution but I was wondering about a concise way to loop through (and compile) all files in the different subdirectories.

3 Answers 3

1
for file in $flist ; do
    "$myCC" -c $myCFLAGS "$file.c" -o "$BLDDIR/$file.o"
done

But using arrays would be cleaner.

for file in "${flist[@]}" ; do
    "$myCC" -c "${myCFLAGS[@]}" "$file.c" -o "$BLDDIR/$file.o"
done
Sign up to request clarification or add additional context in comments.

Comments

0

First, the items to be looped over aren't enclosed in any punctuation; if you supply them literally, it looks like this:

for file in file1 file2 file3; do
  ...
done

Second, how are you populating the variable flist? Ideally, it should be an array, which can be created with literal values like this:

flist=(file1 file2 file3...)

but if you're getting it as the output of some other command then It takes a bit more work to turn that into an array.

You would loop over such an array like this:

for file in "${flist[@]}"; do
...
done

You could just have flist be a string of filenames and do for file in $flist; do (note lack of quotes), but that breaks if any of the filenames contain whitespace etc.

2 Comments

The content of flist is directly declared in a previous statement (it's a long script). Thanks.
If it's a list in csh ( set flist=(name1 name2 name3) ) then the equivalent bash ( flist=(name1 name2 name3) ) gets you an array which you need to use the "${flist[@]}" syntax to loop over.
0

The first problem is pretty simple, the syntax for a for loop in bash is:

for file in [ $flist ]
do
    $myCC -c $myCFLAGS $file.c -o $BLDDIR/$file.o
done

However the next problem is going to be bash does not have a -c option, and I'm not familiar with c shell so I'm not 100% sure what you're trying to do here.

Hope this helps, but if you need additional assistance, just let me know what specifically you're trying to do with each file and I can give you an example in bash

1 Comment

The -c flag is for the compiler but I now understand what I was doing wrong. Thanks.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.