Reading command line arguments

Fish Shell:
Reading command line arguments

How to:

Let’s say greet.fish is your script. You want it to take a name and spit out a greeting.

#!/usr/bin/env fish

# The arguments are stored in $argv
# $argv[1] is the first argument, $argv[2] the second, and so on.

set name $argv[1]
echo "Hello, $name!"

Run it:

$ fish greet.fish World
Hello, World!

Now, with multiple arguments:

#!/usr/bin/env fish

# Loop through all arguments
for arg in $argv
    echo "Hello, $arg!"
end

Try it:

$ fish greet.fish Earth Mars Venus
Hello, Earth!
Hello, Mars!
Hello, Venus!

To handle flags (like -u for uppercase):

#!/usr/bin/env fish

# Check for a "-u" argument
set -l uppercase_mode off
for arg in $argv
    if test "$arg" = "-u"
        set uppercase_mode on
    else if set -q uppercase_mode[1]; and string match --quiet -- "$uppercase_mode" "on"
        echo (string upper "$arg")
    else
        echo $arg
    end
end

And invoke:

$ fish greet.fish -u mercury venus
MERCURY
VENUS

Deep Dive

Fish Shell has had command line arguments nailed down for a long time, much like other shells. What sets Fish apart is its simplicity by design. There’s no $1, $2... $n to remember; it’s an array $argv, familiar territory if you dabble in other programming languages.

There are alternatives, like bash, zsh, etc., but Fish’s scripting syntax aims to be more readable and straightforward. Instead of traditional shift commands or dealing with $@ for all arguments, Fish has that friendly $argv and lovely scripting constructs like for loops and if conditions that are less about cryptic symbols and more about clear words.

When implementing, it’s vital to consider how your script will be used. Will it need default values? Will users know what to input? Make sure you handle cases where users forget to pass arguments or pass them in the wrong order.

See Also