Assign the same string to multiple variables
In my opinion you're better of just doing the more readable:
var1="$value" var2="$value" var3="$value" var4="$value" var5="$value" var6="$value" var7="$value" var8="$value" var9="$value" var10="$value"
But if you want a very short way of accomplishing this then try:
declare var{1..10}="$value"
Edited: using brace expansions instead of printf and declare instead of eval, which could be dangerous depending on what's in $value
.
Cf. EDIT1: You could still use brace expansions in the new case:
declare var{T,z,3}="$value"
It's safer than the printf
approach in the comments because it can handle spaces in $value
.
let
is doing an arithmetic evaluation. In bash
, this is equivalent to (( ... ))
. This is why your code only works for integers.
Using an array instead of specially named variables:
var=( "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" "$value" )
printf 'var[5]=%s\n' "${var[5]}"
or an associative array,
declare -A var
var=( ["T"]=$value ["z"]=$value [3]=$value )
printf 'var[T]=%s\n' "${var["T"]}"
You could also do a loop:
for varname in var0 var1 varT varfoo; do
declare -n var="$varname"
var=$value
done
This loop loops over names of variables. In the loop body, a name reference variable is created that references the current loop variable. When the value of the name reference variable is set, the named variable is set.
value=balabala
eval var{1..10}=\$value
echo $var{1..10}