0

I'm trying to write a bash file which normally takes 3 arguments normally. There is an extra condition which is invoked when there are more than 3 arguments given. This condition should export the extra arguments to a text file called excess. This is the code I have so far:

if [ $# -gt 3]; then
   for ((i = 4; i <= $#; i++)); do
       echo "$i" >> "excess.txt"    
   done
fi

Instead of exporting the actual arguments, the loop is exporting the numbers 4,5,6... to the text file.

I'm not quite sure why this is happening seeing that I've used the dollar sign before 'i' in the echo statement.

codeforester
  • 28,846
  • 11
  • 78
  • 104

2 Answers2

1

You should use indirect expansion ${!}:

for ((i = 4; i <= $#; i++)); do
    echo "${!i}" >> "excess.txt"
done

also, you can do

shift 3; echo "$@" >> execss.txt
Diego Torres Milano
  • 57,580
  • 7
  • 101
  • 124
1

You can do this with one line:

printf '%s\n' "${@:4}" > excess.txt

"${@:4}" expands to "$4" "$5" "$6" ..., and the printf command has its own loop to output its format string once per argument.

chepner
  • 389,128
  • 51
  • 403
  • 529