0
#!/bin/sh

own1="jack"
own2="mark"
own3="black"
    read n "insert number [1-3]"
    echo $own{n}

the purpose is substitution own[1-3] variable with new n variable

1 Answer 1

2

You'd use an indirect variable (documented in the 4th paragraph of Shell Parameter Expansion)

varname="own$n"
echo "${!varname}"

Or in bash version 4.3+, use a nameref

declare -n name="own$n"
echo "$name"

But this is much easier with arrays:

own=(jack mark black)              # an array with 3 elements
read -p "insert number [1-3] " n   # use `-p` option to set the prompt

# TODO validate n is actually a number in the correct range

# bash arrays are zero-indexed, so
echo "${own[n - 1]}"

For elememnts of a numerically indexed array, the index is an arithmetic expression.

However, to ask the user to select one of a number of options, use the select command:

own=(jack mark black)
PS3="Choose a name: "
select name in "${own[@]}"; do
  [[ -n $name ]] && break
done
echo "you chose $name"
Sign up to request clarification or add additional context in comments.

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.