Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fish shell: Check if argument is provided for function

I am creating a function (below) with which you can provide an argument, a directory. I test if the $argv is a directory with -d option, but that doesn’t seem to work, it always return true even if no arguments are supplied. I also tried test -n $argv -a -d $argv to test is $argv is empty sting, but that returns test: Missing argument at index 1 error. How should I test if any argument is provided with the function or not? Why is test -d $argv not working, from my understanding it should be false when no argument is provided, because empty string is not a directory.

function fcd
     if test -d $argv
         open $argv
     else
         open $PWD
     end
 end

Thanks for the help.

like image 563
user14492 Avatar asked Apr 14 '15 18:04

user14492


People also ask

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.

Does Fish read Bashrc?

bashrc and . profile, this file is always read, even in non-interactive or login shells. The “~/. config” part of this can be set via $XDG_CONFIG_HOME, that's just the default.

Where do I put my fish function?

For the first issue, all functions live in your home directory under ~/. config/fish/functions . They're automatically loaded to the list of functions you can access from the fish shell, so there's no need to add the directory to the path yourself.

How do I change my fish prompt?

Prompt Tab The "prompt" tab displays the contents of the current fish shell prompt. It allows selection from 17 predefined prompts. To change the prompt, select one and press "Prompt Set!". DANGER: This overwrites ~/.


2 Answers

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
    end
end

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

like image 80
ridiculous_fish Avatar answered Oct 08 '22 14:10

ridiculous_fish


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
    end
end
like image 32
steevee Avatar answered Oct 08 '22 15:10

steevee