2

I need to print the argument number of which user types in. No matter what I do I always get just an empty line

echo "Give argument number"
read number
allV=$@
echo ${allV[$number]}

what is wrong with this few lines? Even if I start the script with a few arguments and I just manually write sth like"

echo ${allV[1]}

again all I get is an empty line.

1
  • Your assignment to allV does not create an array; therefore, indexing it like an array doesn't help. Use allV=( "$@" ) and echo "${allV[$number]}". Commented May 15, 2016 at 7:53

2 Answers 2

2

Bash lets you use an indirect reference, which works also on numbered parameters:

echo "${!number}"

It also lets you slice the argument list:

echo "${@:$number:1}"

Or you could copy the arguments into an array:

argv=("$@")
echo "${argv[number]}"

In all cases, the quotes are almost certainly required, in case the argument includes whitespace and/or glob characters.

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

Comments

1

To handle $@ as an array, just change it to ("$@") :

echo "Give argument number"
read number
allV=("$@")
echo ${allV[$number-1]}

Comments

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.