在我当前的脚本中,我使用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)
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
编辑7/13/2016:
还有一个额外的':'在删除之后,脚本不再出错。
while getopts "ab:c:" opt; do
修正:
while getopts "abc:" opt; do
答案 0 :(得分:2)
read
从标准输入读取,而不是命令行参数。要么明确指定要读取的文件:
while IFS= read -r line; do # Assume the file ends with a newline
...
done < "$1"
或使用输入重定向将文件提供给脚本:
testscript.sh -ab -c 10 < somefile.txt