【问题标题】:How to create files in the shell where variables are not replaced如何在不替换变量的shell中创建文件
【发布时间】:2022-12-18 15:35:18
【问题描述】:

我需要创建一个文件供后续nohup执行,该文件包含一些变量,我不希望通过文件生成时变量是replaced。 当我在生成的脚本中使用以下代码执行代码时,all the variables were replaced,这不是我所期望的。

#!/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 "$@" 

请问如何更改我的代码?我真的很感激任何帮助。

【问题讨论】:

    标签: bash shell


    【解决方案1】:

    要在此处文档中禁用扩展,请引用分隔符:

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

    相反,让 bash 序列化函数。

    #!/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 "$@"
    

    用 shellcheck 检查你的脚本。不要定义名为test的函数,已经有一个超标准命令test,它是命令[的别名。

    【讨论】:

      猜你喜欢
      • 2012-12-18
      • 2014-12-06
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2018-07-18
      • 2014-01-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多