简体   繁体   English

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

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

Hi I am trying to make a shell script.嗨,我正在尝试制作 shell 脚本。

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

$(whereis -b zsh) makes an error with zsh: command not found zsh: $(whereis -b zsh)使用zsh: command not found zsh:

The error seems to occur because the output of whereis -b zsh is zsh: /usr/bin/zsh /usr/lib/x86_64-linux-gnu/zsh /bin/zsh /etc/zsh /usr/share/zsh /home/linuxbrew/.linuxbrew/bin/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

Now I would like to use /usr/bin/zsh for the script as an output.现在我想使用/usr/bin/zsh作为 output 的脚本。 Is there any way to get the second word from the output of whereis -b zsh ?有没有办法从whereis -b zsh的 output 得到第二个字?

how should the script look like to get what I need?脚本应该如何获得我需要的东西? shell script is quite difficult than I thought. shell 脚本比我想象的要难。 Thank you everyone in advance!提前谢谢大家!

Better add quotes around commands expansion更好地在命令扩展周围添加引号

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

Alternate method by getting zsh from the $PATH :通过从$PATH获取zsh的替代方法:

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

If you run it under bash:如果在 bash 下运行:

Instead of parsing the output of whereis, use type :代替解析 whereis 的 output ,使用type

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

Don't forget that type -P yields an empty string, if the program you are searching for is not in the PATH.如果您要搜索的程序不在 PATH 中,请不要忘记type -P会产生一个空字符串。

If it is not bash, you can also do a如果不是bash,也可以做一个

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

Note that which issues an error message if the program can't be found, so if you need an empty output in this case you'll have to throw away stderr.请注意which如果找不到程序,则会发出错误消息,因此如果在这种情况下您需要一个空的 output,您将不得不丢弃 stderr。

UPDATE : Thinking of it, IMO a better solution is the one suggested by Lea Gris: command -v is available on bash and POSIX shells, and yields empty output if the file can't be found.更新:考虑到这一点,IMO 更好的解决方案是 Lea Gris 建议的解决方案: command -v在 bash 和 POSIX shell 上可用,如果找不到文件,则会产生空的 output。

You can do something like:您可以执行以下操作:

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

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

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