Reputation: 1872
#!/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
Upvotes: 0
Views: 45
Reputation: 247210
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"
Upvotes: 2