0

I'm doing some data analysis in bash with various tools and every now and then I enter something like

>some_command -with -complicated -arguments

Often I immediately follow this up with

>echo "some_command -with -complicated -arguments" >> mylog.txt

Is there any way to do this all at once? It's a pain to hit the up arrow, add echo and quotes so forth.

I don't want to log my entire session, I should add, because there would be a lot of stuff not worth recording.

Ben S.
  • 3,415
  • 7
  • 22
  • 43

2 Answers2

0
verbose () {
  echo "$@" >> mylogfile
  "$@"
}

verbose sleep 1 # "sleep 1" is the example command
DigitalRoss
  • 143,651
  • 25
  • 248
  • 329
  • 1
    This will log `-foo "bar baz"` identically to `-foo bar baz`. – Charles Duffy Jan 27 '17 at 19:55
  • 1
    If you just need semantic equivalence to the command the user ran, consider: `verbose() { local cmd_q; printf -v cmd_q '%q ' "$@"; printf '%s\n' "${cmd_q% }" >>mylogfile; "$@"; }` -- but that's just semantic equivalence, it's not the precise text (and, say, `verbose cat - "$(something)" >elsewhere` won't log either the redirection *or* the knowledge that it was the output of `something` used to form the last argument before said redirection). – Charles Duffy Jan 27 '17 at 19:58
  • Yeah this is a problem. For example `sed -i "s/Alice/Bob/g" test.txt` is logged as `sed -i s/Alice/Bob/g test.txt`. I'd like the exact original command stored. – Ben S. Jan 27 '17 at 20:13
0

Following the references pointed out by Charles Duffy, I ended up adding this to my .bashrc:

logit() {
    fc -ln -1 | sed '1s/^[[:space:]]*//' >> ${1:-commands.txt}
}

So logit by itself will add the last command to commands.txt, and logit myfile will add the last command to myfile.

Ben S.
  • 3,415
  • 7
  • 22
  • 43