0

Is there a way to evaluate any string variable, when the string/variable name has been defined inside a script? Answer: Yes. See below. Note how it handles various kinds of whitespace.

#!/bin/bash  
function infunction () {
printf '%s\n' '--- next ---'
printf '%s\n' 'hard-coded variable name "dog":'
printf 'BEGIN|'
printf '%s' "$dog"
printf '|END'
printf '\n'
printf '%s\n' 'parameter expansion by printf:'
printf 'BEGIN|'
printf '%s' "${!nameofvariable}"
printf '|END'
printf '\n'
}
nameofvariable='dog'
dog='pig'
infunction
dog='    -   pig     '
infunction
dog=' '
infunction
dog=$'\n'
infunction
dog=$'\t'
infunction
Jacob Wegelin
  • 1,304
  • 11
  • 16
  • 1
    Can you show your output and how it differs from what you expected? – Benjamin W. Aug 07 '18 at 20:54
  • Keep in mind that `printf` or `echo`, like any other command, is only invoked **after** the paramater expansions for their argument lists are complete. They can't change how the expansion takes place; the only difference is how they deal with the resulting arguments. – Charles Duffy Aug 07 '18 at 21:03
  • So it's not accurate to think of it as "parameter expansion by printf" or "parameter expansion by echo"; your difference is only how between how `echo` or `printf` deal with the lists (yes, **lists**) that result from unquoted expansions. (If your unquoted expansion is empty or contains only characters in IFS -- whitespace by default -- then the list as well will be empty). – Charles Duffy Aug 07 '18 at 21:04
  • Run `bash -x yourscript`, and the reasoning for your results will be clearer (if the behavior is still unclear, [edit] a simplified test case into the question with the actual results, and explain in detail exactly what part of those results is surprising to you and why). And also add `"${!nameofvariable}"`, **with the quotes**, to what you're testing; that distinction should be a usefully clarifying one as well. – Charles Duffy Aug 07 '18 at 21:05
  • I'd also suggest code of the form `printf 'BEGIN|%s|END\n' "$dog"` to improve compactness and thus readability. – Charles Duffy Aug 07 '18 at 21:07
  • BTW, as an aside, see the notes in http://wiki.bash-hackers.org/scripting/obsolete re: the `function` keyword. – Charles Duffy Aug 07 '18 at 21:25
  • BTW, note that `printf` repeats its format string after all arguments are consumed, so `printf '%s\n' "first line" "second line" "third line"` emits three separate lines. – Charles Duffy Aug 07 '18 at 21:26

0 Answers0