Reputation: 4815
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
Upvotes: 2
Views: 7478
Reputation: 10541
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.
Upvotes: 2
Reputation: 212208
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
Upvotes: 2