简体   繁体   中英

Iterating through argument list using for loop in shell script?

I want to display the contents of the files supplied to my shell script via arguments. I need to do this using the normal 'for (())' loop and NOT the 'for x in arr' loop.

This is my code. How should i put the file name correctly for that cat command?

for (( i=1;$i<=$#;i=$i+2 ))
do
    cat '$'$i   #display the contents of the file currently being traversed
done

You can use something like:

for (( i=1;$i<=$#;i=$i+1 ))
do
    cat ${!i}  #display the contents of the file currently being traversed
done

The corresponding manual section:

If the first character of parameter is an exclamation point, a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion. The exceptions to this are the expansions of ${.prefix*} and ${.name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection.

The normal behavior of a for loop is to iterate over the arguments. To iterate over all arguments:

#!/bin/sh -e
for x; do cat $x; done

You can modify that slightly to only operate on every other argument as you do in your example in many different ways. One possibility is:

for x; do expr $(( i++ )) % 2 > /dev/null || cat "$x"; done

If you insist on using the non-standard form, you can use the ${,var} bashism which will fail in the great majority of shells, or you can use eval

for (( i = 1; i <= $#; i += 2 ))
do
    eval cat '"$'$i\"
done

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM