7

Related to this question on shell scripts and echoing command: In a shell script: echo shell commands as they are executed

I'd like to do something like this:

foo() {
  cmd='ls -lt | head'
  echo $cmd
  eval ${cmd}
}

I tried this:

foo2() {
  set -x
  ls -lt | head
  set +x
}

but that generates this extra ouput

+foo2:2> ls -G -lt
+foo2:2> head
total 136
drwxr-xr-x  18 justin  staff    612 Nov 19 10:10 spec
+foo2:3> set +x

Is there any more elegant way to do this in a zsh function?

I'd like to do something like this:

foo() {
  cmd='ls -lt | head'
  eval -x ${cmd}
}

and just echo the cmd being run (maybe with expansion of aliases).

Community
  • 1
  • 1
justingordon
  • 12,553
  • 12
  • 72
  • 116

2 Answers2

14

setopt verbose

Put that wherever you want to start echoing commands as they are run, and when you don't want that behavior, use

unsetopt verbose

P.S. I realize this thread is too old to answer the original questioner, but wanted to help anyone who runs across this question in the future.

Jon Carter
  • 2,836
  • 1
  • 20
  • 26
  • Good option, but it's a bit wordier than my `echoRun` function for permanent installation. However, I'd say this is a great option for debugging. – justingordon Mar 01 '16 at 02:29
  • 1
    Well, you could always shorten it to 'set -o verbose', add it to your .zshrc, and never worry with it again. :) Or, more realistically, just set the option at the top of the script, and everything in the script will be echoed as it is evaluated. Once the script terminates, the option is not carried back to the shell, so there's nothing to unset. I prefer setting the option for a 'set it and forget it' style, if I want to see *every* command as it is run, but your echoRun() provides better debug resolution for analyzing the behavior only of certain commands or blocks. – Jon Carter Mar 02 '16 at 23:17
3

This worked for me. I defined this zsh function:

echoRun() {
  echo "> $1"
  eval $1
}

Then I run the command inside a function like this:

foo() {
  echoRun "ls -lt | head"
}

Any better option?

justingordon
  • 12,553
  • 12
  • 72
  • 116