简体   繁体   中英

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

Hi I am trying to make a shell script.

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

$(whereis -b zsh) makes an error with 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

Now I would like to use /usr/bin/zsh for the script as an output. Is there any way to get the second word from the output of whereis -b zsh ?

how should the script look like to get what I need? shell script is quite difficult than I thought. 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 :

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

If you run it under bash:

Instead of parsing the output of whereis, use 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.

If it is not bash, you can also do a

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.

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.

You can do something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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