简体   繁体   English

用可选参数编​​写鱼壳脚本

[英]Writing A Fish Shell Script With an Optional Argument

I have a fish shell script whose default behavior is to send an email when complete. 我有一个fish shell脚本,其默认行为是在完成后发送电子邮件。 I'd like to modify it to respond to a nomail argument from the command line. 我想修改它以响应命令行中的nomail参数。 So, for example, running the script normally would produce an email: 因此,例如,正常运行脚本会生成一封电子邮件:

michaelmichael: ~/bin/myscript

But if run with the nomail switch, it wouldn't send the confirmation email: 但如果使用nomail开关运行,它将不会发送确认电子邮件:

michaelmichael: ~/bin/myscript nomail

If I run the script with the nomail argument, it runs fine. 如果我使用nomail参数运行脚本,它运行正常。 Without nomail , $argv is undefined and it throws an error. 没有nomail$argv是未定义的,它会抛出错误。 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

Running this throws the following error: 运行此命令会引发以下错误:

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. 显然它需要一个参数,我只是不知道告诉它不接受任何参数的语法,或者它是否存在的语法。

I'm guessing this is pretty basic, but I just don't understand shell scripting very well. 我猜这是非常基本的,但我只是不太了解shell脚本。

Wrap your switch statement like this: 像这样包装你的switch语句:

if set -q argv
    ...
end

Also, I think your default case should be case '*' . 另外,我认为你的默认情况应该是case '*'

If you prefer using switch statement it's also possible: 如果您更喜欢使用switch语句,那么它也是可能的:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM