BASH, getopts 传递参数以及逐行读取文件
BASH, getopts to pass arguments as well as read file line by line
在我当前的脚本中,我使用 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
编辑 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 < ""
或使用输入重定向将文件提供给您的脚本:
testscript.sh -ab -c 10 < somefile.txt
在我当前的脚本中,我使用 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
编辑 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 < ""
或使用输入重定向将文件提供给您的脚本:
testscript.sh -ab -c 10 < somefile.txt