我有一个包含大量变量的文件。
$ cat message.txt
Hello, ${LOCATION}! You too, ${PERSON} ;)如果未定义PERSON,则envsubst将其替换为nothing:
$ LOCATION=World envsubst < message.txt
Hello, World! You too, ;)如果文件中的许多环境变量没有定义,我如何使非零退出代码(或可靠的) envsubst失败?
发布于 2022-12-01 21:04:49
这并不理想,因为它不会按照请求改变envsubst的行为,但是它能够识别未设置的变量。用户必须确保分隔符EOF不会出现在文本中。如果是,则选择不同的分隔符。
#!/usr/bin/env bash
msg="$( printf 'cat << EOF\n%s\nEOF\n' "$(cat)" )"
bash -u <<< "$msg"输出:
$ ./test.sh < message.txt || echo fail
bash: line 1: LOCATION: unbound variable
fail
$ LOCATION=World ./test.sh < message.txt || echo fail
bash: line 1: PERSON: unbound variable
fail
$ LOCATION=World PERSON=Ralph ./test.sh < message.txt || echo fail
Hello, World! You too, Ralph ;)下面是一个更长的版本,它将一次列出所有未设置的变量,而不是一次只公开一个变量:
#!/usr/bin/env bash
check_vars() {
# pass a list of variable names on stdin, one to a line
rc=0
while read v
do
if [[ ! "${!v}" ]]
then
printf '%s\n' "$v"
rc=1
fi
done
return $rc
}
envsubst -v "$(cat)" | check_vars此版本将输出一个未设置(或null)变量列表,其中一个输出到一行,并在列表为空的情况下以0退出。
输出:
$ ./test2.sh < message.txt || echo fail
LOCATION
PERSON
fail
$ PERSON=Ralph ./test2.sh < message.txt || echo fail
LOCATION
fail
$ LOCATION=World ./test2.sh < message.txt || echo fail
PERSON
fail
$ LOCATION=World PERSON=Ralph ./test2.sh < message.txt || echo fail
$发布于 2022-12-01 20:05:28
在perl中,您可以很容易地达到等效的值,如果未定义env,则可以通过错误退出:
perl -pe 's{\$(?|\{(\w+)\}|(\w+))}{$ENV{$1} // die "A1 not defined\n"}ge'https://unix.stackexchange.com/questions/689046
复制相似问题