tags:

views:

77

answers:

5

I need to process the shared library dependencies of a library from a bash script. The for command processes word-by-word:

for DEPENDENCY in `otool -L MyApplication | sed 1d`
do
    ...
done

What is the way to process the results line-by-line?

A: 

You can use awk to process things on a per-line basis. Exactly what's the best way depends on what you're trying to do though.

Daniel Egeberg
+5  A: 

You should use the read command.

otool -L MyApplication | sed 1d | \
while read i
do
  echo "line: " $i
done

See bashref for a description of the read builtin, and its options. You can also have a look at the following tutorial for examples of using read in conjunction with for.

tonio
Warning: if you need to set variables in the while loop (i.e. store what you found in otool's output), they'll vanish as soon as the loop exits because it's part of a pipeline and therefore runs in a subshell. In bash, you can get around this with a bit of rearranging: `while read i; do ... done < <(otool -L MyApplication | sed 1d)`
Gordon Davisson
+6  A: 
otool -L MyApplication | sed 1d | while read line ;
do
  # do stuff with $line
done
Jim Lewis
+2  A: 

Try changing the Internal Field Separator to a newline. By default, bash is going to separate tokens by spaces when using a for loop. Your IFS setting will make the for loop split up the tokens based on whatever string IFS is equal to (thus splitting up the list tokens by newlines instead of by tokens by spaces).

[bash ] $ IFS="
"
[bash ] $ for DEPENDENCY in `otool -L MyApplication | sed 1d`
do
    ....
done
noneme
A: 

you can do it awk as well. No need to use a bash for loop

otool -L MyApplication | awk 'NR>1
{
  # do your stuff here since awk process line by line.
}' 
ghostdog74