getopts在bash脚本中不工作
并且得到了输出getopts在bash脚本中不工作,bash,unix,Bash,Unix,并且得到了输出 #! bin/bash # code for train.sh while getopts "f:" flag do case $flag in f) echo "Hi" STARTPOINT = $OPTARG ;; esac done echo Test range: $4 echo
#! bin/bash
# code for train.sh
while getopts "f:" flag
do
case $flag in
f)
echo "Hi"
STARTPOINT = $OPTARG
;;
esac
done
echo Test range: $4
echo Train range: $3
#path of experiment folder and data folder:
EXP_DIR="$1"
DATA_DIR="$2"
echo Experiment: $EXP_DIR
echo DataSet: $DATA_DIR
echo file: $STARTPOINT
I ran the command > ./train.sh test1 test2 test3 test4 -f testf
所以getopts选项似乎由于某种原因不起作用,因为您可以看到文件后面没有打印任何内容,而且case语句中也没有执行echo“Hi”命令。有人能帮我吗?您需要在参数前添加任何选项
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file:
有输出
./train.sh -f testf test1 test2 test3 test4
你也需要一些改变
Hi
Test range: test4
Train range: test3
Experiment: test1
DataSet: test2
file: testf
要设置环境变量并将got选项移开,请执行以下两点操作:
while
,getopts
函数在循环中不需要移位。但是,当getopts完成后,需要进行移位以处理非选项参数。变量OPTIND
表示要分析的下一个非选项的索引,该值可在shift
命令中使用
下面是一个示例,其中我还包括用于“帮助”、“norun”和“详细”标志的h
、n
和v
选项:
而getopts'f:hnv'opt;做
案例“$opt”加入
h) 用法;;
n) norun=1;;
f) 回音“嗨”;STARTPOINT=“$OPTARG”;;
v) 详细=1;;
以撒
完成
班次$((可选项-1))
是可以在位置参数之后有getopts,还是必须在位置参数之前有getopts?为什么在case语句内部和外部使用两个移位?一个移位处理-f,另一个处理testf。因此,如果有一个没有参数的选项,代码将更加通用。您可能可以shift
关闭您的裸参数,然后调用getopt
,以便在完成Aks后处理任何选项以获得解释。这很有帮助
while getopts "f:" flag
do
case $flag in
f)
echo "Hi"
STARTPOINT=$OPTARG
shift
;;
esac
shift
done
while getopts 'f:hnv' opt ; do
case "$opt" in
h) usage ;;
n) norun=1 ;;
f) echo "Hi" ; STARTPOINT="$OPTARG" ;;
v) verbose=1 ;;
esac
done
shift $(( OPTIND - 1 ))