我昨天开发的代码采用文件(x.txt)或空格分隔的数字(434 435 436 437)作为输入,并将数据从fron大小写在数组中并循环遍历。运行带有标志的shell脚本作为命令行参数
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=([email protected]);
fi
for testCase in "${testCases[@]}"
do
echo "Running Testcases $testCase"
done
我想这样做,使之容易出错
我想实际上有一个标志与文件运行上面的脚本作为paramenter
而少的方式SH test.sh -f MYFILE.TXT
,或者可以与-t flasg运行用数字作为论据
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脚本的工作就在昨天,和IAM真的很短的如何做到这一点语法
最后,如果我们有标记的文件或标记的数字参数(根本没有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=([email protected]);
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
请咨询任何帮助表示赞赏。
感谢 Tejas的
是什么转移$(($ OPTIND - 1)),以及如果有两个号码和文件标志... 发布一个新的代码为这个scenario.please检查和咨询 – user2256825
的'shift'删除选项已经被''$ @“'(位置参数列表)中的'getopts'使用过,只留下非选项参数。显示的代码已经接受了文件和一些数字;它只需要一个文件或一些数字,但不会诊断文件和一些数字。调整测试以满足您的需求。 –
是的,现在的要求是有数字和文件的标志。我会尝试查看我们的代码,并会根据情况更换我的,谢谢 – user2256825