简体   繁体   中英

How to combine two strings and use it as a variable?

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

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"
}

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

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

=> 1234

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM