How to switch PATH in fish shell – with example script

Posted: October 22nd, 2021 | Author: | Filed under: Server side | No Comments »

fish is a Unix shell with a focus on interactivity and usability. Fish is designed to give the user features by default, rather than by configuration.[4] Fish is considered an exotic shell since it does not rigorously adhere to POSIX shell standards, at the discretion of the maintainers. en.wikipedia.org/wiki/Fish_(Unix_shell)

Although being "an exotic shell" once installed you'd never want to remove it since it proves so useful in the daily tasks. However, one of the annoying side effects is that it is not easy to remove paths from the PATH variable, which is required when wanting to change the environment. Here is an example:  changing from PHP74 to PHP72 on a MacOS, for both the CLI and FPM configurations.

Scripts to switch PHP versions from PHP72 to PHP74

> cat ~/fish_php74.sh

#!/usr/bin/env fish

#remove PHP72
for argv in /usr/local/opt/[email protected]/bin /usr/local/opt/[email protected]/sbin;
    while contains $argv $fish_user_paths
        set -l index (contains -i $argv $fish_user_paths)
        set –erase –universal fish_user_paths[$index]
    end
end

#add PHP74
for argv in /usr/local/opt/[email protected]/bin /usr/local/opt/[email protected]/sbin;
    if contains $argv $fish_user_paths
        echo "Path already contains $argv"
    else
fish_add_path $argv
    end
end

echo $fish_user_paths | tr " " "\n" | nl

brew services stop [email protected]
brew services start [email protected]

Run it:

> ~/fish_php74.sh

     1 /usr/local/opt/[email protected]/sbin

     2 /usr/local/opt/[email protected]/bin

Stopping `[email protected]`… (might take a while)

==> Successfully stopped `[email protected]` (label: [email protected])

==> Successfully started `[email protected]` (label: [email protected])

Scripts to switch PHP versions from PHP74 to PHP72

> cat ~/fish_php72.sh

#!/usr/bin/env fish

#remove PHP74
for argv in /usr/local/opt/[email protected]/bin /usr/local/opt/[email protected]/sbin;
    while contains $argv $fish_user_paths
        set -l index (contains -i $argv $fish_user_paths)
        set –erase –universal fish_user_paths[$index]
    end
end

#add PHP72
for argv in /usr/local/opt/[email protected]/bin /usr/local/opt/[email protected]/sbin;
    if contains $argv $fish_user_paths
        echo "Path already contains $argv"
    else
        fish_add_path $argv
    end
end

echo $fish_user_paths | tr " " "\n" | nl

brew services stop [email protected]
brew services start [email protected]

 

Run it:

~/fish_php72.sh

     1 /usr/local/opt/[email protected]/sbin

     2 /usr/local/opt/[email protected]/bin

Stopping `[email protected]`… (might take a while)

==> Successfully stopped `[email protected]` (label: [email protected])

==> Successfully started `[email protected]` (label: [email protected])