Home > Blockchain >  How to create files in the shell where variables are not replaced
How to create files in the shell where variables are not replaced

Time:12-07

I need to create a file for subsequent nohup execution, the file contains some variables, I don't want the variables to be replaced when I generate through the file. When I executed the code with the following code, all the variables were replaced in the generated script, which was not what I expected.

#!/bin/bash

gen_script() {
    filepath=$1
    if [ ! -f "$filepath" ]; then
    cat >${filepath} <<EOF
#!/bin/bash
# Code generated by main.sh; DO NOT EDIT.

test(){
    ip=$1
    port=$2
    restorefile=$3
    redis-cli -h $ip -p $port --pipe <  $restorefile
}
test "$@"
EOF
    fi
}

main(){
    gen_script exec.sh
    nohup bash exec.sh $1 $2 > nohup.out 2>&1 &
}
main "$@" 

How can I change my code please? I really appreciate any help with this.

CodePudding user response:

To disable expansions in here document, quote the delimieter:

cat <<'EOF'
... $not_expanded
EOF

Instead, let bash serialize the function.

#!/bin/bash

work() {
    ip=$1
    port=$2
    restorefile=$3
    redis-cli -h $ip -p $port --pipe <  $restorefile
}

gen_script() {
    filepath=$1
    if [ ! -f "$filepath" ]; then
       cat >${filepath} <<EOF
#!/bin/bash
# Code generated by main.sh; DO NOT EDIT.
$(declare -f work)
work "\$@"
EOF
    fi
}

main() {
    gen_script exec.sh
    nohup bash exec.sh "$1" "$2" > nohup.out 2>&1 &
}
main "$@"

Check your script with shellcheck. Do not define a function named test, there is already a super standard command test which is an alias for command [.

  • Related