Replace bash variables in template file

前端 未结 1 1420
独厮守ぢ
独厮守ぢ 2021-01-19 07:10

I am attempting to use Bash in order to run a form of an install process. During this process, a configuration file is copied and certain values are replaced inside of it. S

1条回答
  •  遥遥无期
    2021-01-19 07:42

    Security tips

    This don't take care of security issues! Using eval is evil!

    The compatible answer is not better!

    Of course, you have to be confident about the content of your template!!

    If else, try using sed! (see my last answer)

    Quick way bash only!:

    Under bash you can simply:

    eval "INSTALLPATH='/somepath/somewhere' SITEURL='example.com' PHPSERV='127.0.0.1:9000'; echo \"$(

    or

    eval "INSTALLPATH='/somepath/somewhere'
        SITEURL='example.com'
        PHPSERV='127.0.0.1:9000';
        echo \"$(

    As you're using eval, you could store your resulting config file into one variable:

    eval "INSTALLPATH='/somepath/somewhere'
        SITEURL='example.com'
        PHPSERV='127.0.0.1:9000';
        cfgBody=\"$(

    Then

    echo "$cfgBody"
    

    and/or

    echo "$cfgBody" >/cfgpath/cfgfile
    

    Doing this into a loop

    tmplBody="$("$CFGFILE"
      done <<<"
        /somepath/somewhere            example.com  127.0.0.1:9000  /tmp/file1
        '/some\ other\ path/elsewhere' sample2.com  127.0.0.1:9001  /tmp/file2
    "
    

    Note: On second line, there are escaped spaces (prepanded with a backshash \ and quotes '. The backslash tell read to not split the variable, and the quotes have to be added into the resulting /tmp/file2.

    Soft way (compatible answer)

    Under posix shell, you may do this way:

    #!/bin/sh
    
    (
        cat <

    This don't require bash, was tested under dash and busybox.

    bash Without eval !

    sedcmd=''
    for var in INSTALLPATH SITEURL PHPSERV;do
        printf -v sc 's/${%s}/%s/;' $var "${!var//\//\\/}"
        sedcmd+="$sc"
      done
    sed -e "$sedcmd"