2

I would like to get, in the output, the content of KW0_TEXT and KW1_TEXT from the "for" of this script:

#!/bin/sh
STRS=" KW0 KW1 "
KW0_TEXT="text text text"
KW1_TEXT="text text  text text"
for str in ${STRS}; do
echo ${str}_TEXT
eval echo ${str}_TEXT
done

so far, in the output, I got only:

KW0_TEXT
KW0_TEXT
KW1_TEXT
KW1_TEXT
  • The reason eval echo $var isn't working as you expect is because the variable gets expanded first, before eval gets a change to execute. There are tricks you can do to make eval work, but the answers hold better solutions. – glenn jackman Mar 29 '18 at 19:50
4

If your /bin/sh is actually /bin/bash, you can use variable indirection:

#!/bin/bash
STRS=" KW0 KW1 "
KW0_TEXT="text text text"
KW1_TEXT="text text  text text"
for str in ${STRS}; do
  var=${str}_TEXT
  printf "%s\n" "${!var}"
done
3

If your /bin/sh is actually /bin/bash, and your version is fairly recent, you can use an associative array

#!/bin/bash
strs=( KW0 KW1 )
declare -A text=( 
    [KW0]="text text text" 
    [KW1]="text text  text text" 
)
for str in "${strs[@]}"; do 
    printf "%s\t%s\n" "$str" "${text[$str]}"
done
KW0     text text text
KW1     text text  text text
0

The problem is that you're missing a literal $ in your eval use. After the variable is substituted, the command you're evaluating is

echo KW0_TEXT

but you want

echo $KW0_TEXT

It should be:

eval echo '$'${str}_TEXT

However, the indirect variable method of Jeff Schaller is preferable if you're using a shell that supports it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.