0

I have a bash that should be run in this way:

./script.sh <arg1> <arg2> <arg3>...<argn>

I want to show these args in my bash:

<arg3> <arg4> ... <argn>

So I wrote this bash:

for (( i=1; i<=$#-3; i++ ))
do
    echo $((3+i))
done

but it shows me number of args.

How can I put # in order to see my real args?

Thanks

1

5 Answers 5

4

If you want to show arguments starting from arg3, you can simply use

echo "${@:3}" # OR
printf "%s\n" "${@:3}"

If you really want to show argument indices, use

for (( i=3; i < $#; i++)); do 
    echo $i
done
Sign up to request clarification or add additional context in comments.

Comments

3

You can store all arguments in a BASH array and then use them for processing later:

args=( "$@" )
for (( i=2; i<${#args[@]}; i++ ))
do
    echo "arg # $((i+1)) :: ${args[$i]}"
done

Comments

2

A minimal solution that displays the desired arguments without the math:

shift 2
for word
do
  echo ${word} 
done

Comments

1

I prefer @anubhava's solution of storing the arguments in an array, but to make your original code work, you could use eval:

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

3 Comments

Do you mean with a C-style for loop?
with c style and and -3 that I wrote..thank you, my problem is: echo $((3+i))
echo ${!i} is a much better method of performing indirect parameter expansion in bash than using eval.
0

After your all good answers I found this solution that works well for my thread:

ARG=( $(echo "${@:3}") )
for (( i=1; i<=$#-3; i++ ))
do
    echo ${ARG[i]}
done

1 Comment

There's no need to post a separate answer if you accept another.

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.