0

Need to find a way to locate desired variables based on string combination

#!/bin/bash
DSPDSP="1234"
$A="DSP"
$B="DSP"
PORTLIST=$A$B
echo $PORTLIST

DSPDSP

I hope there is a smart function in bash that concerts a string into variable name

smart_echo $PORTLIST

1234

Yeats Raw
  • 109
  • 1
  • 4
  • I think you are looking for a kind of indirect expansion https://stackoverflow.com/questions/8515411/what-is-indirect-expansion-what-does-var-mean – geckos Jan 09 '19 at 03:09

2 Answers2

0

Please try something like:

smart_echo() {
    local varname="$1"
    echo "${!varname}"
}

DSPDSP="1234"
A="DSP"
B="DSP"
PORTLIST="$A$B"
smart_echo "$PORTLIST"

=> 1234

If your bash version is 4.3 or newer, you can also say as an alternative:

smart_echo() {
    declare -n p="$1"
    echo "$p"
}
tshiono
  • 21,248
  • 2
  • 14
  • 22
  • Thanks, based on your input, I found my working version like this: A="DSP" B="DSP" PORTLIST=$A$B echo ${!PORTLIST} => 1234 – Yeats Raw Jan 09 '19 at 04:17
  • Yep. It woks without defining a special function. BTW please make it a practice to **double-quote variables** with a few exceptions (the case an explict word-splitting is required, the pattern matching (regex or comparison) within [[ ... ]], etc.). BR. – tshiono Jan 09 '19 at 05:23
0

Thanks, based on your input, I found my working version like this:

    A="DSP" 
    B="DSP"
    PORTLIST=$A$B 
    echo ${!PORTLIST} 

=> 1234

Yeats Raw
  • 109
  • 1
  • 4
  • Use a *nameref*, e.g. `declare -n PLIST=$A$B; echo $PLIST`. See `"nameref"` in [bash(1) - Linux manual page](http://man7.org/linux/man-pages/man1/bash.1.html) – David C. Rankin Jan 09 '19 at 04:43