I've just come off the Winows wagon, and the gnome-terminal and bash are looking great, but I don't quite know how to get it to do what I want, (I suspect it is possible).
Can std output (eg. from sed) be made to run as a command? (ie. interpret and run the output as part of the script's logic.) I am polling a process to output its status at开发者_如何转开发 timed intervals, and I would like to do it as a one liner.# dd is already running in another terminal. Its PID is 1234
pgrep -l '^dd$' | sed -n 's/^\([0-9]\+.*\)/sudo watch -n 30 kill -USR1 \1/p'
# this outputs: sudo watch 30 kill -USR1 1234
Is there some short-cut terminal/bash magic to run sudo watch 30 kill -USR1 1234
?
Thanks.
You should be able to wrap it in $()
:
$(pgrep ... | sed ...)
But why not do:
while :; do sleep 30; clear; kill -USR1 $(pgrep '^dd$'); done
Wrap it inside $(). $() assigns standard output like an environment variable. On a line by itself, this runs the printed command.
$(pgrep -l '^dd$' | sed -n 's/^\([0-9]\+.*\)/sudo watch -n 30 kill -USR1 \1/p')
Just pipe the commands to sh
:
pgrep -l '^dd$' | sed -n 's/^\([0-9]\+.*\)/sudo watch -n 30 kill -USR1 \1/p' | sh
Just because this comes up relatively high on certain Google searches, I will add this answer.
If you put `` around a command then the output will be re-routed into a string, that if is just by itself will be run as a command.
For instance this will run 'echo 3':
`echo "echo 3"`
Also this can work with multiple layers, for instance:
``echo "echo echo 3"``
Will echo '3', because the first echo gives 'echo echo 3' which launches another echo which gives 'echo 3' which is run.
I always use the `` instead of $() or |sh / |bash because I personally think it looks cleaner inside scripts. But it works almost exactly like $() (I do not believe there are any differences, but there might be slight ones).
One of the things you can do with $() and `` that you can't do with | bash is assigning variables. You can store the output and then execute it later:
azdefvar="`COMMAND_THAT_OUTPUTS_COMMAND`"
Here is an example:
daboross@DaboUbuntu:~$ date +%T
13:09:20
daboross@DaboUbuntu:~$ azdef="`echo "date +%T"`"
daboross@DaboUbuntu:~$ echo $azdef
date +%T
daboross@DaboUbuntu:~$ $azdef
13:09:45
daboross@DaboUbuntu:~$ echo $azdef | bash
13:09:53
You can use $() instead of `` in any of these cases.
The ` key is directly below the esc key on most keyboards.
精彩评论