vishal patil vishal patil - 2 months ago 7
Bash Question

setting variables with variable names in bash (para$i=... giving "command not found")

I want to pass three arguments to a script,the first two numbers and third one any character,Buut when i run the script it says command not found ,even though the value is getting assigned.i have attached the code and image below.enter image description here
This is my peice of code,

#!/bin/bash
if [ $# -lt 3 ]
then
echo "insufficient argument"
for((i=$#+1;i<4;i=$i+1))
do
read -p "enter $i parameter: " x
para$i=x
done
fi

Answer

This is not a valid assignment:

para$i=x

Since your shell is bash, you can do the following instead:

# bash 3.1 or higher
printf -v "para$i" %s "$x"

...or...

# bash 4.3 or higher; works with arrays and other tricky cases too.
declare -n para="para$i"
para=$x
unset -n para

...or...

# any POSIX shell
# be very careful about the quoting; only safe if $x is quoted and $i is a controlled value
eval "para$i=\$x"

See the BashFAQ #6 section on indirect assignment for more details.