1

I have a test script test.sh where I am trying to print out command line arguments.to the script but the following does not work as expected

`#!/bin/bash
 for((i=1;i<"$#";i++)) do
        printf "Position %s of argumentArray has  %s \n", $i  $(($i))
  done`

( my idea was that the (()) will do the mathematical evaluation resulting in $1 $2 etc.) Neither does

for((i=1;i<"$#";i++)) do
printf "Position %s of argumentArray has  %s \n", $i  $"$( eval echo $i )"
done

both gives as out put when run as follows

./test.sh  first second third 

Position 1 of argumentArray has  1 
Position 1 of argumentArray has  2
Position 1 of argumentArray has  3

instead of

Position 1 of argumentArray has  first 
Position 1 of argumentArray has  second
Position 1 of argumentArray has  third

I face the same problem with

for((i=1;i<="$#";i++)) 
  do
      case "$($i)" in
       .......

case evaluates to 1 ,2 3 etc insted of the actual parameter passed in.

Please help me in understanding where I am going wrong.

2 Answers 2

1

You can use indirect expansion to do this fairly easily:

for((i=1;i<=$#;i++)) do
    printf "Position %s of argumentArray has  %s \n" $i  "${!i}"
done

I also fixed some minor problems in the above: the loop end condition should be i<=$# to print the last arg, there shouldn't be a comma after the format string for printf, and there should be double-quotes around the argument ("${!i}") in case it has any spaces or other funny characters.

Sign up to request clarification or add additional context in comments.

Comments

0

The commandline arguments can be accessed directly but if you want them by position you can do this:

arguments=($@)
for ((i = 0; i < ${#arguments[@]}; i++)); do
    echo "arguments[$i] = ${arguments[$i]}"
done

A run of the script:

$ ./args.sh first second third
arguments[0] = first
arguments[1] = second
arguments[2] = third

ADDENDUM

Information on Bash arrays:

1 Comment

Thanks it works. Forgot about arays altogether I went on to do. ` for((i=1;i<"$#";i++)) do str=$( echo $( eval echo \$$( echo $i ))) echo $str printf "Position %s of batchProcessArray has %s \n", $i "$str" done ` but your answer is the best solution. thanks once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.