我想测试是否在我的bash脚本中传递了一个参数(例如-h)。
在Ruby脚本中,可以这样实现:
#!/usr/bin/env ruby
puts "Has -h" if ARGV.include? "-h"
如何在Bash中最好地完成这个任务?
我想测试是否在我的bash脚本中传递了一个参数(例如-h)。
在Ruby脚本中,可以这样实现:
#!/usr/bin/env ruby
puts "Has -h" if ARGV.include? "-h"
如何在Bash中最好地完成这个任务?
if [[ " $@ " =~ " -h " ]]; then
echo "Has -h"
fi
-h
的字符串参数(例如my_command "oh gods -h game over"
),此方法会报告错误的结果。唯一通用的解决方案是按照下面详细说明的方式迭代getopts
结果。</shrug>
- Cecil Curry#!/bin/bash
while getopts h x; do
echo "has -h";
done; OPTIND=0
getopts
循环之间重置OPTIND=0
。 - Jonathan Leffler这个问题比较复杂,最快的方法也不可靠:
case "$*" in
(*-h*) echo "Has -h";;
esac
不幸的是,这也会识别出 "command this-here
" 中的 "-h
"。
通常您可以使用 getopts
来解析您期望的参数:
while getopts habcf: opt
do
case "$opt" in
(h) echo "Has -h";;
([abc])
echo "Got -$opt";;
(f) echo "File: $OPTARG";;
esac
done
shift (($OPTIND - 1))
# General (non-option) arguments are now in "$@"
等等。
我正在尝试以简单但正确的方式解决这个问题,并且只是分享适用于我的方法。
下面的专用函数可以解决它,您可以像这样使用:
if [ "$(has_arg "-h" "$@")" = true ]; then
# TODO: code if "-h" in arguments
else
# TODO: code if "-h" not in arguments
fi
此函数检查第一个参数是否在所有其他参数中:
function has_arg() {
ARG="$1"
shift
while [[ "$#" -gt 0 ]]; do
if [ "$ARG" = "$1" ]; then
echo true
return
else
shift
fi
done
echo false
}