Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

fish

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?

like image 223
Dallas Avatar asked Sep 28 '17 05:09

Dallas


People also ask

What does argv 1 mean in C++?

argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.

Where is the fish shell config file?

Configuration. To store configuration write it to a file called ~/. config/fish/config. fish .

How do I customize my fish shell prompt?

fish is empty by default. To create a custom prompt create a file ~/. config/fish/functions/fish_prompt. fish and fill it with your prompt.

How do you make a function in a fish shell?

By using one of the event handler switches, a function can be made to run automatically at specific events. The user may generate new events using the emit builtin. Fish generates the following named events: fish_prompt , which is emitted whenever a new fish prompt is about to be displayed.


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.

like image 106
ridiculous_fish Avatar answered Oct 13 '22 02:10

ridiculous_fish