How to test for argv count and value of argv[1] in fish shell?

Viewed 5229

I am trying to test for the length of $argv or the value of the first $argv[1] element in a function like follows:

function do-something
  if test (count $argv) -lt 2 -o $argv[1] = "--help"
    echo Usage ...
  end
end

However, I am getting the following error:

⟩ do-something 
test: Missing argument at index 6

The issue is with the string comparison, but I am not sure how to get this working. I have also tried -o [ $argv[1] = "--help" ], but this fails with another error.

Note also that this works if I include an argument, so it seems fish is evaluating the second condition even if the first fails. Is this a bug?

1 Answers

The problem is that (count $argv) and $argv[1] both get expanded at the same time, as they are both arguments to the same command, and $argv[1] is empty if unset. So if there were no arguments, test sees:

if test (count) -lt 2 -o = "--help"

Resulting in an error.

The simplest way to fix this is by quoting $argv[1]:

if test (count $argv) -lt 2 -o "$argv[1]" = "--help"

The quotes ensure that "$argv[1]" expands to one argument (an empty string) instead of no arguments.

An alternative is to use two separate commands:

function do-something
  if test (count $argv) -lt 2; or test $argv[1] = "--help"
    echo Usage
  end
end

The second test will only execute if the first one succeeds.

Related