使用 bash 脚本未绑定变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46664656/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 22:36:35  来源:igfitidea点击:

Unbound variable with bash script

bashshellscripting

提问by k_mishap

Im becoming desperate when debugging my script, I used some constructions recommended to me from my senior collegue and I dont know how to make it work properly.

我在调试脚本时变得绝望,我使用了我的高级同事向我推荐的一些结构,但我不知道如何使其正常工作。

 #!/bin/bash -x
set -ueo pipefail
exec &>/tmp/dq.log
source ${BASH_SOURCE%/*}/env-prd.sh

times=${2:-1}
sleep=${3:-1}

name="all-dq_hourly"


fs_lock_file="/tmp/mwa/jobs/prd-${name}.lock"

( flock -n 200
    log="/var/log/mwa/prd/$(date +%Y-%m-%d)__${name}.log"
    for i in $(seq 1 $times); do
        if [[ ! -f /tmp/stop ]]; then
        couple commands

      fi
        sleep $sleep
    done

) 200>"$fs_lock_file" | tee -a $log

rm $fs_lock_file

From the execs , I can see there is an issue with unbound variable for the tee -a $logpart, couple commandsget executed allright. I tried to use backtics in the log path, but to no benefit. I suspect the same issue with fs_lock_file, but I havent fixed the logging first yet.
Can somebody open my eyes and tell me what Im missing? Im not able to make the script logging to path specified.

从 execs ,我可以看到该tee -a $log部分的未绑定变量存在问题,couple commands可以执行。我尝试在日志路径中使用 backtics,但没有任何好处。我怀疑 fs_lock_file 也有同样的问题,但我还没有先修复日志记录。
有人可以睁开我的眼睛告诉我我错过了什么吗?我无法将脚本记录到指定的路径。

采纳答案by Michael Jaros

You are assigning the variable loginside a subshell([...] ). That variable is not bound outside that subshell.

您正在子外壳[...]log内分配变量。该变量未绑定到该子外壳之外。()

In this case it is probalby best to just set logoutside the subshell, i.e. move the variable assignment before the subshell block.

在这种情况下,最好只log在子外壳之外设置,即在子外壳块之前移动变量赋值。

Generally in similar cases, you could try replacing the subshell parentheses with curly braces (group command syntax) {[...] }.

通常在类似情况下,您可以尝试用大括号(组命令语法{[...] 替换子外壳括号}

Group commands are executed in the current shell. Note that in contrast to subshell syntax, lists must be terminated by newline or semicolon, see Compound Commands in the Lists section of the bash(1) manpage.

组命令在当前 shell 中执行。请注意,与 subshel​​l 语法相反,列表必须以换行符或分号终止,请参阅 bash(1) 联机帮助页的列表部分中的复合命令。

And as a general best practice, setting variable names, especially constants at the beginning of a script or function helps avoid this kind of bug.

作为一般的最佳实践,在脚本或函数的开头设置变量名称,尤其是常量有助于避免此类错误。