Reputation: 161
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!
Upvotes: 1
Views: 744
Reputation: 22217
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.
Upvotes: 1
Reputation: 19555
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)"
Upvotes: 2