Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash: How to use an alias command in combination with watch

Tags:

alias

bash

watch

I would like to use an alias command in bash in combination with the watch command. The watch command is multiple chained commands.

A very simple example how I would think it would work (but it does not):

alias foo=some_command          # a more complicated command
watch -n 1 "$(foo) | grep bar"  # foo is not interpreted as the alias :(
like image 671
User12547645 Avatar asked Feb 21 '19 19:02

User12547645


1 Answers

watch -n 1 "$(foo) | grep sh" is wrong for two reasons.

  1. When watch "$(cmdA) | cmdB" is executed by the shell, $(cmdA) gets expanded before running watch. Then watch would execute the output of cmdA as a command (which should fail in most cases) and pipe the output of that to cmdB. You probably meant watch 'cmdA | cmdB'.

  2. The alias foo is defined in the current shell only. watch is not a built-in command and therefore has to execute its command in another shell which does not know the alias foo. There is a small trick presented in this answer, however we have to make some adjustments to make it work with pipes and options

alias foo=some_command
alias watch='watch -n 1 ' # trailing space treats next word as an alias
watch foo '| grep sh'

Note that the options for watch have to be specified inside the watch alias. The trailing space causes only the next word to be treated as an alias. With watch -n 1 foo bash would try to expand -n as an alias, but not foo.

like image 164
Socowi Avatar answered Oct 25 '22 09:10

Socowi