我昨天开发的下面的代码,以文件(x.txt)或空格分隔的数字(434 435 436 437)作为输入,并将这两种情况中的数据放入数组中并循环。
Syntax: shtest.sh 434 435 436 or sh test.sh x.txt
MYFILE=$1 ;
OLDIFS=$IFS;
IFS=' ';
if [ -f "$MYFILE" ]; then
testCases=($(cat $MYFILE));
else
testCases=($@);
fi
for testCase in "${testCases[@]}"
do
echo "Running Testcases $testCase"
done
我想这样做是为了使它更不容易出错
我想实际上有一个标志,而运行上述脚本与文件作为参数
sh test.sh -f myFile.txt
或者可以使用-t flash以数字作为参数运行
sh test.sh -t 434 435 436
如果-f和-t都存在,那么我必须检查并抛出错误
例如:sh test.sh -f myFile.sh -t 343 435 435或sh test.sh -t 343 435 435 -f myFile.sh
我昨天才开始学习Shell脚本,我真的不知道如何在语法上做到这一点
最后,如果我们有标记的文件或标记的数字参数(没有未标记),下面的代码是否工作或是否有任何问题语法:
sh test.sh -f myFile.txt #should work
sh test.sh -t 443 444 443 443 # should work
sh test.sh -f myFile.txt -t 443 444 443 443 # should fail
isFile=0;
isTest=0;
while getopts ":f:c:t:" opt; do
case $opt in
f)
echo "-f was triggered, Parameter: $OPTARG" >&2
testCases=($(cat $OPTARG));
isFile=1;
;;
t)
# testCases=($@);
multi+=("$OPTARG")
for val in "${multi[@]}"; do
echo " - $val"
done
;;
c)
echo "-c was triggered, Parameter: $OPTARG" >&2;
isTest=1;
;;
?)
echo "Invalid option: -$OPTARG" >&2
exit 1
;;
:)
echo "Option -$OPTARG requires an argument." >&2
exit 1
;;
esac
done
# Exit if both flags are sent
if [ isTest==1 && isFile==1 ]; then
{
echo "Exiting";
}
fi
#if the flag is not avaiable, the store the orphan numbers (Command Line Arguments)
for testCase in "${testCases[@]}"
do
echo "Running Testcases $testCase"
done
请建议和任何帮助是感激的。
谢谢光辉
在while getopts
循环之后,添加:
shift $(($OPTIND - 1))
if [ $isFile = 0 ] && [ $# = 0 ]
then
echo "$0: must specify file (-f file) or numbers" >&2
exit 1
fi
我假设在循环之前有isFile=0
。如果不显式地设置它,就可能继承用户意外设置的环境变量。始终要小心,不要意外地使用调用脚本的代码中的环境变量。