BASH、getopts传递参数以及逐行读取文件
在我当前的脚本中,我使用getopts传递选项设置,然后逐行读取文件BASH、getopts传递参数以及逐行读取文件,bash,getopts,Bash,Getopts,在我当前的脚本中,我使用getopts传递选项设置,然后逐行读取文件 #! /bin/bash GetA=0 GetB=0 while getopts "ab:c:" opt; do case "$opt" in a) GetA=1 echo "-a get option a" ;; b) GetB=1 echo "-b get option b" ;; c)
#! /bin/bash
GetA=0
GetB=0
while getopts "ab:c:" opt; do
case "$opt" in
a)
GetA=1
echo "-a get option a"
;;
b)
GetB=1
echo "-b get option b"
;;
c)
c=${OPTARG}
;;
esac
done
shift "$((OPTIND -l ))"
while IFS='' read -r line || [[ -n "$line" ]]; do
echo $line
echo "GetA is " $GetA
echo "GetB is " $GetB
echo "c is " $c
done
现在,如果使用以下命令行运行此脚本:
testscript.sh -ab -c 10 somefile.txt
预期结果:
$ line1 from somefile.txt
GetA is 1
GetB is 1
c is 10
但是,给出了一个错误:
/testscript.sh: line number: No such file or directory
2016年7月13日编辑: 在b之后有一个额外的“:”在删除它之后,脚本不再给出错误
while getopts "ab:c:" opt; do
更正:
while getopts "abc:" opt; do
read
读取标准输入,而不是命令行参数。或者显式指定要从中读取的文件:
while IFS= read -r line; do # Assume the file ends with a newline
...
done < "$1"
而IFS=read-r行;是否假定文件以换行符结尾
...
完成<“$1”
或使用输入重定向将文件馈送到脚本:
testscript.sh -ab -c 10 < somefile.txt
testscript.sh-ab-c10
您可能需要一个代码>终止您的b)
案例。您的b:
定义需要一个参数,但示例命令行没有传递一个参数。您是正确的。Optoin b后面不应该有“:”。我修好了,现在问题解决了。