Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Writing A Fish Shell Script With an Optional Argument

Tags:

shell

fish

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.

like image 501
michaelmichael Avatar asked Jun 25 '10 13:06

michaelmichael


People also ask

How do you indicate optional arguments?

To indicate optional arguments, Square brackets are commonly used, and can also be used to group parameters that must be specified together. To indicate required arguments, Angled brackets are commonly used, following the same grouping conventions as square brackets.

How do I customize my fish shell prompt?

Prompt Tab The "prompt" tab displays the contents of the current fish shell prompt. It allows selection from 17 predefined prompts. To change the prompt, select one and press "Prompt Set!".

How do you write a fish script?

To be able to run fish scripts from your terminal, you have to do two things. Add the following shebang line to the top of your script file: #!/usr/bin/env fish . Mark the file as executable using the following command: chmod +x <YOUR_FISH_SCRIPT_FILENAME> .

How do you set up a fish shell?

You can make FSH your default shell on the terminal via two simple steps: Add the line /usr/local/bin/fish to the /etc/shells file (it may already be there depending on how you have installed the shell). This is assuming FSH was installed in /usr/local/bin, as is the default location for when it is compiled.


1 Answers

Wrap your switch statement like this:

if set -q argv
    ...
end

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

like image 84
Dennis Williamson Avatar answered Sep 21 '22 12:09

Dennis Williamson