var=4
com="$(echo "A\nB\nC\nD" | sed 's/\\n/\n/g')"
seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed "s/$/ <<< \"\$(echo \"\$com\")\"/g"
Above outputs: read var1 var2 var3 var4 <<< "$(echo "$com")" What i want is to execute that command instead of outputing and echo all four set variables using && after it has been executed
Tried:
`seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed "s/$/ <<< \"\$(echo \"\$com\")\"/g"` && echo $var1 $var2 $var3 $var4
Doesn't work
Tried:
seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed "s/$/ <<< \"\$(echo \"\$com\")\"/g" | bash
Above doesn't work because variables are set in seperate session not globally
Tried:
eval "seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed \"s/$/ <<< \"\$(echo \"\$com\")\"/g"\" && echo $var1 $var2 $var3 $var4
But doesn't work. Pleae help needed.
Desired output: After all variables set: A B C D
seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed "s/$/ <<< \"\$(echo \"\$com\")\" \&\& echo \$var1 \$var2 \$var3 \var4/g" | bash
Above may work but $com is not expanding inside sed
CodePudding user response:
Finally Got It Worked
var=4
com="$(echo "A\nB\nC\nD" | sed 's/\\n/\n/g')"
seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed "s/$/ <<< \"\$(echo `echo $com`)\" \&\& echo \$var1 \$var2 \$var3 \$var4/g" | bash
CodePudding user response:
Finally Solved
var=4
com="$(echo "A\nB\nC\nD" | sed 's/\\n/\n/g')"
eval "seq "$var" | sed 's/^/var/g' | xargs | sed 's/^/read /g' | sed \"s/$/ <<< \$\(echo `echo $com`\) \&\& echo \\\$var1 \\\$var2 \\\$var3 \\\$var4/g\"" | bash
CodePudding user response:
Assumptions:
- objective is to define and populate four new variables:
var1=A
,var2=B
,var3=C
andvar4=D
- optionally
export
the variables
Generating the variable names and values:
$ $ printf "var%s\n" {1..4}
var1
var2
var3
var4
$ printf "%s\n" {A..D}
A
B
C
D
Associate variable names with values:
$ paste <(printf "var%s\n" {1..4}) <(printf "%s\n" {A..D})
var1 A
var2 B
var3 C
var4 D
Short demo of a bash nameref:
$ typeset -p myvar
-bash: typeset: myvar: not found
$ declare -n newvar="myvar"
$ newvar='new_value'
$ typeset -p newvar myvar
declare -n newvar="myvar"
declare -- myvar="new_value"
$ echo "${newvar}"
new_value
$ echo "${myvar}"
new_value
From here we can use a while
loop and a nameref
to create and populate the new variables:
# verify variables do not exist:
$ typeset -p var1 var2 var3 var4
-bash: typeset: var1: not found
-bash: typeset: var2: not found
-bash: typeset: var3: not found
-bash: typeset: var4: not found
# create/populate/export new variables
while read -r name val
do
declare -n x="${name}"
export x="${val}"
done < <(paste <(printf "var%s\n" {1..4}) <(printf "%s\n" {A..D}))
# verify variables now exist, are populated and exported (-x):
$ typeset -p var1 var2 var3 var4
declare -x var1="A"
declare -x var2="B"
declare -x var3="C"
declare -x var4="D"