【问题标题】:Running a ShellScript with flags for the command line arguments运行带有命令行参数标志的 Shell 脚本
【发布时间】: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

我想这样做以减少出错的可能性

  1. 我想在运行上述脚本时实际有一个标志,并以文件作为参数

    sh test.sh -f myFile.txt

    或者可以使用 -t flags 以数字作为参数运行

    sh test.sh -t 434 435 436

  2. 如果 -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

请提供建议,我们将不胜感激。

谢谢 光辉

【问题讨论】:

    标签: bash shell freebsd


    【解决方案1】:

    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。如果您没有明确设置它,您可能会继承用户意外设置的环境变量。请始终注意不要意外使用调用脚本的代码中的环境变量。

    【讨论】:

    • 什么移位 $(($OPTIND - 1)) ,如果有数字和文件的标志怎么办...发布了这个场景的新代码。请检查和建议
    • shift"$@"(位置参数列表)中删除getopts“使用”的选项,只留下非选项参数。显示的代码已经接受了一个文件和一些数字;它只需要一个文件或一些数字,但不会同时诊断一个文件和一些数字。调整测试以满足您的需求。
    • 是的,现在要求对 numbers 和 file 都有标志。我将尝试查看您的代码并相应地更改我的代码,谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-15
    • 1970-01-01
    • 2013-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多