views:

26

answers:

1

I have a fish shell script whose default behavior is to send an email when complete. I'd like to modify it to respond to a nomail argument from the command line. 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:

michaelmichael: ~/bin/myscript nomail

If I run the script with the nomail argument, it runs fine. Without 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

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.

+1  A: 

Wrap your switch statement like this:

if set -q argv
    ...
end

Also, I think your default case should be case '*'.

Dennis Williamson
That worked (though `nomail` has to be the default case, not '*'). Here's what I changed it to: `if set -q argv; switch $argv; case nomail; echo Not sending mail.; case '*'; echo Unspecified switch.; end; else; echo sending mail.; end`
michaelmichael
@michaelmichael: By default case, I mean the default of the `switch` statement which is executed if none of the specified cases match. Exactly how you have the code in your comment. Sorry, I misread your original code and mistook "???" as if it were intended to be the `switch` default.
Dennis Williamson