Create variable from string/nameonly parameter to extract data in bash?

前端 未结 3 744
别那么骄傲
别那么骄傲 2020-12-12 03:31

I want to save the variable name and its contents easily from my script.

Currently :-

LOGFILE=/root/log.txt
TEST=/file/path
echo \"TEST : ${TEST}\" &         


        
相关标签:
3条回答
  • 2020-12-12 04:11

    Consider using the printenv function. It does exactly what it says on the tin, prints your environment. It can also take parameters

    $ printenv
    SSH_AGENT_PID=2068
    TERM=xterm
    SHELL=/bin/bash
    LANG=en_US.UTF-8
    HISTCONTROL=ignoreboth
    ...etc
    

    You could do printenv and then grep for any vars you know you have defined and be done in two lines, such as:

    $printenv | grep "VARNAME1\|VARNAME2"
    VARNAME1=foo
    VARNAME2=bar
    
    0 讨论(0)
  • 2020-12-12 04:32

    Yes, using indirect expansion:

    echo "$1 : ${!1}"
    

    Quoting from Bash reference manual:

    The basic form of parameter expansion is ${parameter} [...] If the first character of parameter is an exclamation point (!), a level of variable indirection is introduced. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself. This is known as indirect expansion

    0 讨论(0)
  • 2020-12-12 04:33

    You want to use Variable Indirection. Also, don't use the function keyword, it is not POSIX and also not necessary as long as you have () at the end of your function name.

    LOGFILE=/root/log.txt
    
    save()
    {
        echo "$1 : ${!1}" >> ${LOGFILE}
    }
    
    TEST=/file/path
    
    save TEST
    

    Proof of Concept

    $ TEST=foo; save(){ echo "$1 : ${!1}"; }; save TEST
    TEST : foo
    
    0 讨论(0)
提交回复
热议问题