我有一个以getopts开头的脚本,如下所示:
USAGE() { echo -e "Usage: bash $0 [-w <in-dir>] [-o <out-dir>] [-c <template1>] [-t <template2>] \n" 1>&2; exit 1; }
if (($# == 0))
then
USAGE
fi
while getopts ":w:o:c:t:h" opt
do
case $opt in
w ) BIGWIGS=$OPTARG
;;
o ) OUTDIR=$OPTARG
;;
c ) CONTAINER=$OPTARG
;;
t ) TRACK=$OPTARG
;;
h ) USAGE
;;
\? ) echo "Invalid option: -$OPTARG exiting" >&2
exit
;;
: ) echo "Option -$OPTARG requires an argument" >&2
exit
;;
esac
done
more commands etc
echo $OUTDIR
echo $CONTAINER
我对老头子很陌生。我在这个脚本上做了一些测试,在某个阶段,我不需要/不想使用-c参数-c。换句话说,我试图测试脚本的另一个特定部分,根本不涉及$CONTAINER变量。因此,我简单地在所有命令前面添加了#和$CONTAINER,并做了一些测试,这是很好的。
在不使用$CONTAINER测试脚本时,我输入了以下内容:
bash script.bash -w mydir -o myoutdir -t mywantedtemplate
然而,我想知道,鉴于我的头领命令,我没有收到警告。换句话说,为什么我没有收到关于-c论点的警告。这个是可能的吗?此警告是否仅在我键入:
bash script.bash -w mydir -o myoutdir -t mywantedtemplate -c
更新
在做了一些测试之后,我想这就是:
这是正确的吗?
发布于 2018-09-14 11:42:42
当不使用某些选项(即它们是可选的)时,getopts
不会发出警告。通常,这是一件好事,因为有些选项(例如-h
)不与其他选项一起使用。没有办法直接用Bash内置的getopts
指定强制选项。如果您想要强制选项,那么您需要编写代码来检查它们是否已被使用。见bash getopts with multiple and mandatory options。此外(正如您已经发现的),如果您不能编写代码来处理optstring
(first)参数中指定给getopts
的选项,则不会出现错误。
通过在Bash代码中使用nounset
设置(使用set -o nounset
或set -u
),您可以获得强制参数的自动警告。如果没有指定echo $CONTAINER
选项,因此不会设置$CONTAINER
,这将导致对像-c
这样的代码发出警告。但是,使用nounset
选项将意味着需要更仔细地编写代码的所有。有关更多信息,请参见How can I make bash treat undefined variables as errors?,包括注释和“链接”答案。
发布于 2021-11-24 03:02:31
您可以使用以下脚本:
printf
捕获stdout
并放入stderr
,然后返回到stdout
也捕获exit
代码,因此如果代码大于0
,我们可以处理。
some_command() {
echo 'this is the stdout'
echo 'this is the stderr' >&2
exit 1
}
run_command() {
{
IFS=$'\n' read -r -d '' stderr;
IFS=$'\n' read -r -d '' stdout;
(IFS=$'\n' read -r -d '' _ERRNO_; exit ${_ERRNO_});
} < <((printf '\0%s\0%d\0' "$(some_command)" "${?}" 1>&2) 2>&1)
}
echo 'Run command:'
if ! run_command; then
## Show the values
typeset -p stdout stderr
else
typeset -p stdout stderr
fi
只需将some_command
替换为getopts ":w:o:c:t:h"
https://stackoverflow.com/questions/52319119
复制