getops在提供参数时仍执行默认操作

时间:2015-03-06 20:29:46

标签: bash shell

我最近开始在bash中使用getopts命令。我很困惑为什么我的脚本在提供参数时运行dafult动作“cat~bin / Temp / log.txt | ~bin / Scripts / report.pl”。如果没有参数传递给shell脚本,我只想运行它。我已经使用了getopts:std in perl,我可以编写像:

这样的代码
unless ($opts{d}) {
do something...}

我如何在shell脚本中编写类似的东西?另外,我将如何编写如下的逻辑:

if ($opts{c}) {
    cat ~bin/Temp/mag.txt | ~bin/Scripts/report.pl -c
}
elsif ($opts{d} {
    cat ~bin/Temp/mag.txt | ~bin/Scripts/report.pl -d

我的代码:

#!/bin/sh
while getopts cd name
do
        case $name in
          c)copt=1;;
          d)dopt=1;;
             *)echo "Invalid arg";;
        esac
done

if [[ ! -z $copt ]] #Specifies what happens if the -c argument was provided
then
   echo "CSV file created!"
    cat "~/bin/Temp/log.txt" | ~/bin/Scripts/vpnreport/report.pl -c
fi
if [[ ! -z $dopt ]] #Specifies what happens if the -d argument was provided
then
   echo "Debug report and files created"
    cat ~bin/Temp/mag.txt | ~bin/Scripts/report.pl -d
fi

if [[ ! -z $name ]]     #Specifies what happens if no argument was provided 
then
    echo "Running standard VPN report"
    cat ~bin/Temp/log.txt | ~bin/Scripts/report.pl
fi 

shift $(($OPTIND -1))

我的输出:

[~/bin/Scripts/report]$ sh getoptstest.sh
Running standard report
[~/bin/Scripts/report]$ sh getoptstest.sh -d
Debug report and files created
Running standard report
[~/bin/Scripts/report]$

两个getopts命令与bash到perl有很大的不同,即使在阅读了几个教程后我也似乎无法获得bash varient的挂起。任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

getopts的最后一次运行中,您的变量(name)将设置为“?”。

#!/bin/bash
while getopts abc foo; do :; done
echo "<$foo>"

以上输出:

$ ./mytest.sh 
<?>
$ ./mytest.sh -a
<?>

Insead,使用elif,就像Perl的elsif

if [[ ! -z $copt ]]
then
  # ...
elif [[ ! -z $dopt ]]
then
  # ...
else
  # ...
fi

或测试if [[ -z $copt && -z $dopt ]],等等。其他说明:

答案 1 :(得分:0)

我接受了Jeff的回答并重新编写了我的脚本,现在它可以正常工作:

#!/bin/bash
while getopts cd name
do
    case $name in
      c)carg=1;;
      d)darg=1;;
         *)echo "Invalid arg";;
    esac
done
#Specifies what happens if the -c argument was provided:
if [[ ! -z $carg ]]
    then
    if [[ -z $darg ]]
        then
            echo "CSV created"
            cat ~bin/Temp/log.txt | ~bin/Scripts/report.pl -c
else 
    echo "Debug CSV created"
    cat ~bin/Temp/log.txt | ~bin/Scripts/report.pl -cd
    fi
fi
#Specifies what happens if the -d argurment was provided:
if  [[ ! -z $darg ]]
    then
    echo "Debug report created"
    cat ~bin/Temp/log.txt | ~bin/Scripts/report.pl -d
#Specifies what happens if no  argument was provided:
else
    echo "Standard report created"
    cat ~bin/Temp/logs.txt | ~bin/Scripts/report.pl
fi

再次感谢您的协助!