代码之家  ›  专栏  ›  技术社区  ›  michaelmichael

用可选参数编写鱼壳脚本

  •  9
  • michaelmichael  · 技术社区  · 14 年前

    我有一个鱼壳脚本,它的默认行为是在完成时发送电子邮件。我想修改它以回应 nomail 来自命令行的参数。例如,运行脚本通常会生成一封电子邮件:

    michaelmichael: ~/bin/myscript

    但如果和 提名 切换,它不会发送确认电子邮件:

    michaelmichael: ~/bin/myscript nomail

    如果我用 提名 争论,一切正常。没有 提名 , $argv is undefined and it throws an error. I've scoured the fish shell documentation, but can't seem to find anything that will work. Here's what I have so far

    switch $argv
      case nomail
        ## Perform normal script functions
      case ???
        ## Perform normal script functions
        mailx -s "Script Done!"
    end
    

    运行此操作会引发以下错误:

    switch: Expected exactly one argument, got 0

    Obviously it expects an argument, I just don't know the syntax for telling it to accept no arguments, or one if it exists.

    我猜这是非常基本的,但我只是不太了解shell脚本。

    2 回复  |  直到 9 年前
        1
  •  9
  •   Dennis Williamson    14 年前

    包装你的 switch 如下声明:

    if set -q argv
        ...
    end
    

    另外,我认为你的默认情况应该是 case '*' .

        2
  •  6
  •   Jakub Kubrynski    11 年前

    如果您喜欢使用switch语句,也可以:

    switch (echo $argv)
      case nomail
        ## Perform normal script functions
      case '*'
        ## Perform normal script functions
        mailx -s "Script Done!"
    end