Fish shell: Check if argument is provided for function Fish shell: Check if argument is provided for function shell shell

Fish shell: Check if argument is provided for function


count is the right way to do this. For the common case of checking whether there are any arguments, you can use its exit status:

function fcd    if count $argv > /dev/null        open $argv    else        open $PWD    endend

To answer your second question, test -d $argv returns true if $argv is empty, because POSIX requires that when test is passed one argument, it must "Exit true (0) if $1 is not null; otherwise, exit false". So when $argv is empty, test -d $argv means test -d which must exit true because -d is not empty! Argh!

edit Added a missing end, thanks to Ismail for noticing


In fish 2.1+ at least, you can name your arguments, which then allows for arguably more semantic code:

function fcd --argument-names 'filename'    if test -n "$filename"        open $filename    else        open $PWD    endend


$argv is a list, so you want to look at the first element, if there are elements in that list:

if begin; test (count $argv) -gt 0; and test -d $argv[1]; end    open $argv[1] else    open $PWDend