How to switch PATH in fish shell – with example script
Posted: October 22nd, 2021 | Author: admin | 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/php@7.2/bin /usr/local/opt/php@7.2/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/php@7.4/bin /usr/local/opt/php@7.4/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 php@7.2
brew services start php@7.4
Run it:
> ~/fish_php74.sh
1 /usr/local/opt/php@7.4/sbin
2 /usr/local/opt/php@7.4/bin
Stopping `php@7.2`… (might take a while)
==> Successfully stopped `php@7.2` (label: homebrew.mxcl.php@7.2)
==> Successfully started `php@7.4` (label: homebrew.mxcl.php@7.4)
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/php@7.4/bin /usr/local/opt/php@7.4/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/php@7.2/bin /usr/local/opt/php@7.2/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 php@7.4
brew services start php@7.2
Run it:
~/fish_php72.sh
1 /usr/local/opt/php@7.2/sbin
2 /usr/local/opt/php@7.2/bin
Stopping `php@7.4`… (might take a while)
==> Successfully stopped `php@7.4` (label: homebrew.mxcl.php@7.4)
==> Successfully started `php@7.2` (label: homebrew.mxcl.php@7.2)