How to create files in the shell where variables are not replaced
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 c开发者_如何学Goan I change my code please? I really appreciate any help with this.
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 [
.
精彩评论