Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active November 12, 2023 19:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YumaInaura/bec7488cdd654e1221894d7c3d7aa5a8 to your computer and use it in GitHub Desktop.
Save YumaInaura/bec7488cdd654e1221894d7c3d7aa5a8 to your computer and use it in GitHub Desktop.
Bash — split $PATH by colon and for in

Bash — split $PATH by colon and for in

for i in $(echo "$PATH" | sed 's/:/ /g'); do echo $i;  done;
  • Replace colon to space in $PATH
  • Pass to for command space separated $PATH
  • for command ( foo roop ) catches that strings as multiple arguments ( so not quote string )
    • So double quotationed string pattern does not work well because for command get in string one argument. ( e.g "$(echo "$PATH" | sed 's/:/ /g')" )

Output example

bash-4.4$ for i in $(echo "$PATH" | sed 's/:/ /g'); do echo $i;  done;
/Users/yuma/.rbenv/shims
/Users/yuma/.rbenv/bin
/Users/yuma/.rbenv/shims
/Users/yuma/.rbenv/bin
./vendor/bin
/Users/yinaura/google-cloud-sdk/bin
/usr/local/opt/openssl/bin
/Users/yuma/.pyenv/shims
/usr/local/bin
/usr/bin
/bin
/usr/sbin
/sbin

Other example

get first of $PATH

for i in $(echo "$PATH" | sed 's/:/ /g'); do echo $i; done | head -n 1
/Users/yuma/.rbenv/shims

get last of $PATH

for i in $(echo "$PATH" | sed 's/:/ /g'); do echo $i; done | tail -n -1
/sbin

Maybe

Use awk is better?

Versions

  • GNU bash, version 4.4.23(1)-release (x86_64-apple-darwin17.5.0)

Links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment