s-leg3ndz
s-leg3ndz

Reputation: 3528

convert bash script to fish

I would like convert a Bash script to a Fish script to test if file .nvmrc exists.

Bash script:

## Auto load nvm when there's a .nvmrc file
OLD_PWD=""
promptCommand() {
    if [ "$OLD_PWD" != "$PWD" ] ;
        then
        OLD_PWD="$PWD"
        if [ -e .nvmrc ] ;
            then nvm use;
        fi
    fi
}
export PROMPT_COMMAND=promptCommand

And Fish script (don't work):

set OLD_PWD ""
function nvm_prompt
    if [ "$OLD_PWD" != "$PWD" ]
        then
        OLD_PWD="$PWD"
        if [ -e .nvmrc ]
            then bass source ~/.nvm/nvm.sh --no-use ';' nvm use
        end
    end
end

Upvotes: 0

Views: 3421

Answers (1)

faho
faho

Reputation: 15924

First of all, fish's if does not use the word then. It's just gone.

So

if [ "$OLD_PWD" != "$PWD" ]
    then

becomes just

if [ "$OLD_PWD" != "$PWD" ]

(and similarly with the other if)

Secondly,

OLD_PWD="$PWD"

isn't valid fish script (as it'll have told you). Use

set -g OLD_PWD "$PWD"

Thirdly, as it stands, this function is currently defined but never run. You need some way to execute it when the PWD changes. And, as luck would have it, fish has a way to define functions to run on variable changes - the --on-variable VARNAME option to function.

So your solution would look something like this:

function nvm_prompt --on-variable PWD
    if [ "$OLD_PWD" != "$PWD" ] 
        set -g OLD_PWD "$PWD"
        if [ -e .nvmrc ]
            bass source ~/.nvm/nvm.sh --no-use ';' nvm use
        end
    end
end

You might even do away with the $OLD_PWD check, or you might not, since the event is also triggered when you do e.g. cd . (i.e. when the variable is set again to the same value).

Also, I'm assuming the name means that it is run when the prompt is displayed, not that it actually displays anything by itself - in which case you'd stick it in your fish_prompt function (try funced fish_prompt and funcsave fish_prompt).

Upvotes: 3

Related Questions