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?
argv[1] indicates the first argument passed to the program, argv[2] the second argument, and so on.
Configuration. To store configuration write it to a file called ~/. config/fish/config. fish .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With