Parsing path in ZSH


Lately i’ve had to work with a new operating system (apple) and it’s built in shell is ZSH.

With that i’ve had to understand how to parse strings in it compared to KSH and Bash. One interesting thing I found is that that the standard $PATH variable in zsh is already split into an array for you in this variable $path. So to test and see if something is in your path like BASH you can simply use that variable to your advantage like this:


getBashVersion()
{
  for p in $path;do
    b="$p/bash"
    if [[ -f "$b" ]]; then
       echo "_____$(echo $p)______"
       $b --version | grep version
       echo "_____________"
    else
      echo "no bash found in $p"
    fi
  done

}

Once you’ve sourced this in your profile you can run like this:

> getBashVersion

no bash found in /Users/username/py3/bin
_____/usr/local/bin______
GNU bash, version 5.1.16(1)-release (x86_64-apple-darwin21.1.0)
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
_____________
no bash found in /usr/bin
_____/bin______
GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin21)
_____________
no bash found in /usr/sbin
no bash found in /sbin
no bash found in /usr/local/MacGPG2/bin
no bash found in /Users/username/src/Python/environments/ekp-regress/bin
no bash found in /Users/username/.cargo/bin
no bash found in /Users/username/.cargo/bin

Hopefully this helps someone

Until then keep scripting

thom

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s