以人类可读的方式显示 PATH

以人类可读的方式显示 PATH

我想以更易于理解的方式显示我的 PATH 环境变量。

$ echo $PATH
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin:/Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin:/Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin:/Users/arturo/.rvm/bin:/usr/local/git/bin:/Users/arturo/.gvm/groovy/current/bin:/Users/arturo/.gvm/grails/current/bin:/Users/arturo/.gvm/griffon/current/bin:/Users/arturo/.gvm/gradle/current/bin:/Users/arturo/.gvm/lazybones/current/bin:/Users/arturo/.gvm/vertx/current/bin:/Users/arturo/.gvm/bin:/Users/arturo/.gvm/ext:/usr/local/git/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin:/usr/local/git/bin

我在想这样的事情:

$ echo $PATH | some cut and awk magic
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin
/Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin
/Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin
/Users/arturo/.rvm/bin
...

答案1

您可以使用tr

$ tr ':' '\n' <<< "$PATH"
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin
/Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin
/Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin
...

您还可以在某些 shell 中执行此操作(在 bash 和 zsh 中测试):

echo -e ${PATH//:/\\n}

在 zsh 中,您可以使用$path变量来查看带有空格而不是冒号的路径。

$ echo $path
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin /Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin /Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin /Users/arturo/.rvm/bin

可以与printf或组合print

$ printf "%s\n" $path
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin
/Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin
/Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin
...
$ print -l $path
/Users/arturo/.rvm/gems/ruby-1.9.3-p392/bin
/Users/arturo/.rvm/gems/ruby-1.9.3-p392@global/bin
/Users/arturo/.rvm/rubies/ruby-1.9.3-p392/bin
...

这些<<<运算符在这里被称为字符串。这里的字符串将其右侧的单词传递到其左侧命令的标准输入。

$ cat <<< 'Hello there'
Hello there

如果您的 shell 不支持它们,请使用echo管道。

$ echo 'Hello there' | cat
Hello there

答案2

这是一个快速的方法bash

OLDIFS=$IFS IFS=: arr=($PATH) IFS=$OLDIFS
printf "%s\n" "${arr[@]}"

答案3

扩展于史密斯·约翰的解决方案,这会在您的中提供一个很好的别名.bash_profile

alias MyPath='echo -e ${PATH//:/\\n}'

答案4

我发现sed使用管道更直观:

$ echo $PATH | sed 's/:/\n/g'

它用换行符 ( ) 替换:分隔元素的字符,将每个元素显示在单独的行中。$PATH\n

或者,如果您愿意tr(我经常这样做),您也可以实现相同的目标:

$ echo $PATH | tr ':' '\n'

相关内容