【发布时间】:2016-12-18 04:05:57
【问题描述】:
我昨天开发的以下代码将文件(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 flags 以数字作为参数运行
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 脚本,我真的不知道如何在语法上做到这一点
最后,如果我们有标记的文件或标记的数字参数(根本没有 Unfalgged),下面的代码会工作还是会有任何问题 语法:
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
请提供建议,我们将不胜感激。
谢谢 光辉
【问题讨论】: