0

After the question In a shell script: echo shell commands as they are executed I wonder how can I redirect the command executed/echoed to a file (or a variable)?

I tried the usual stdout redirection, like ls $HOME > foo.txt, after setting the bash verbose mode, set -v, but only the output of ls was redirected.

PS: What I want is to have a function (call it "save_succ_cmdline()") that I could put in front of a (complex) command-line (e.g, save_succ_cmdline grep -m1 "model name" /proc/cpuinfo | sed 's/.*://' | cut -d" " -f -3) so that this function will save the given command-line if it succeeds.

Notice that the grep -m1 "model name" ... example above is just to give an example of a command-line with special characters (|,',"). What I expect from such a function "save_succ_cmdline()" is that the actual command (after the function name, grep -m1 "model name"...) is executed and the function verifies the exit code ([$? == 0]) to decide if the command-line can be save or not. If the actual command has succeeded, the function ("save_succ_cmdline") can save the command-line expression (with the pipes and everything else).

My will is to use the bash -o verbose feature to have and (temporarily) save the command-line. But I am not being able to do it.

Thanks in advance.

Community
  • 1
  • 1
Brandt
  • 5,058
  • 3
  • 28
  • 46
  • It is unclear what `grep -m1 "model name" /proc/cpuinfo | sed 's/.*://' | cut -d" " -f -3` is doing with `save_succ_cmdline` function. Can you clarify? – anubhava Jan 05 '15 at 13:58
  • Right. I edited the question in the hope it is clearer. – Brandt Jan 05 '15 at 14:20
  • `grep -m1 "model name"` would be run against the command itself rather than the output of entered command? – anubhava Jan 05 '15 at 14:22

1 Answers1

0

Your save_succ_cmdline function will only see the grep -m1 "model name" /proc/cpuinfo part of the command line as the shell will see the pipe itself.

That being said if you just want the grep part then this will do what you want.

save_succ_cmdline() {
    "$@" && cmd="$@"
}

If you want the whole pipeline then you would need to quote the entire argument to save_succ_cmdline and use eval on "$@" (or similar) and I'm not sure you could make that work for arbitrary quoting.

Etan Reisner
  • 77,877
  • 8
  • 106
  • 148
  • Yeah. That's the point. I need to deal with the special chars. If I flag up the verbose mode (`set -v`) I can have the given cmd-line echoed, with all the pipes, quotes, etc. – Brandt Jan 05 '15 at 14:22
  • The verbose output appears to go to the shell's `stderr` (same place the prompt goes) so you likely can't do much with that. – Etan Reisner Jan 05 '15 at 14:26