Why doesn't the "watch" command work on an alias?
So I've made my customized alias command and tried to use it with alias
, but my alias was not recognized while concatenated with the watch
command.
So I tried to make a thread of it and fortunately, this one helped me out.
But what is the reason for this?
I've created an alias in my .bashrc
which works perfectly fine.
alias gpu='sensors nouveau-pci-0100'
alias cpu='sensors coretemp-isa-0000'
and when I concatenate watch
and gpu
like this:
watch GPU
I get this below every 2 seconds:
sh: 1: gpu: not found
And I solved it regarding the mentioned thread above like this:
alias = watchh='watch '
watchh gpu
But why does this happen? Why can' It use my surely defined alias command?
My guess is it is something about the user because I've gone root once and I couldn't use my alias but I surely need an expert to answer this.
It's nothing to do with users.
Aliases are only expanded in the interactive shell for which they are defined - so an interactive bash shell if you defined them via ~/.bashrc
, or an interactive zsh shell if you define them in ~/.zshrc
for example.
The watch
command invokes commands via a non-interactive /bin/sh
shell.
By aliasing watch
itself, as alias watchh='watch '
(with a trailing space) and then using watchh gpu
, you force the current interactive shell to expand gpu
before it's passed to watch
.
Note that in zsh
, aliases may be defined as global which allows them to be expanded anywhere in a command - avoiding the need to alias watch
with a trailing space.
The watch
command does not locate aliases, only commands in your search path. As an alternative, define gpu
and cpu
as shell scripts instead of aliases and place them in your search path. Then your watch gpu
and watch cpu
commands will work fine.
For example, if $HOME/bin
is a directory in your search path, create a file $HOME/bin/gpu
containing the line:
sensors nouveau-pci-0100
Make the file executable:
$ chmod +x $HOME/bin/gpu
and you're ready to go!
$ watch gpu
Then do the same for cpu
.