繁体   English   中英

如何从 shell 中的命令中获取 output 的第二个字?

[英]How to get the second word of an output from a command in shell?

嗨,我正在尝试制作 shell 脚本。

sudo usermod -s $(whereis -b zsh) $(whoami)

$(whereis -b zsh)使用zsh: command not found zsh:

错误似乎是因为whereis -b zsh的 output 是zsh: /usr/bin/zsh /usr/lib/x86_64-linux-gnu/zsh /bin/zsh /etc/zsh /usr/share/zsh /home/linuxbrew/.linuxbrew/bin/zsh

现在我想使用/usr/bin/zsh作为 output 的脚本。 有没有办法从whereis -b zsh的 output 得到第二个字?

脚本应该如何获得我需要的东西? shell 脚本比我想象的要难。 提前谢谢大家!

更好地在命令扩展周围添加引号

sudo usermod -s "$(whereis zsh | cut -d ' ' -f2)" "$(whoami)"

通过从$PATH获取zsh的替代方法:

sudo usermod -s "$(command -v zsh)" "$(id -un)"

如果在 bash 下运行:

代替解析 whereis 的 output ,使用type

sudo usermod -s "$(type -P zsh)" "$(whoami)"

如果您要搜索的程序不在 PATH 中,请不要忘记type -P会产生一个空字符串。

如果不是bash,也可以做一个

sudo usermod -s "$(which zsh)" "$(whoami)"

请注意which如果找不到程序,则会发出错误消息,因此如果在这种情况下您需要一个空的 output,您将不得不丢弃 stderr。

更新:考虑到这一点,IMO 更好的解决方案是 Lea Gris 建议的解决方案: command -v在 bash 和 POSIX shell 上可用,如果找不到文件,则会产生空的 output。

您可以执行以下操作:

whereis -b zsh | awk '{print $2}'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM