简体   繁体   中英

How to redirect echoed shell commands as they sre executed

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 (eg, 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM