0

I need to run some commands like mentioned below and it should be display on screen before it execute and then output of the command

lsuser -f root|grep -i maxage|awk -F= '{print$2}'

Returns 13.

I tried like storing command in variable as below, but it didn't work.

mxage="lsuser -f root|grep -i maxage|awk -F= '{print$2}'"
echo "$maxage"
echo "`$maxage`"

output should be like:

lsuser -f root|grep -i maxage|awk -F= '{print$2}' 13

Sriram P
  • 179
  • 1
  • 13
  • you want to run _what_ before _what_ ? – Inian Jan 26 '17 at 15:31
  • Sorry [I closed as a duplicate](http://stackoverflow.com/posts/41876885/revisions). I just focused on the last part of the question, while the ultimate goal here is clearly different. Thanks @chepner for undoing it. – fedorqui Jan 26 '17 at 15:34

2 Answers2

1

First, I'd recommend simply using set -x, which logs commands to standard error before they are executed. You can disable this after you are done with set +x.

set -x 
lsuser -f root|grep -i maxage|awk -F= '{print$2}'
set +x

Drawbacks:

  1. The data is written to standard error, not standard output. (In newer versions of bash, though, you can specify an arbitrary file descriptor by setting BASH_XTRACEFD.)
  2. The execution of set +x is traced as well.

If you set the value of the variable very carefully, you can use eval.

cmd="lsuser -f root|grep -i maxage|awk -F= '{print\$2}'"
echo "$cmd"
eval "$cmd"

However, I do not recommend this approach. It is, in theory, possible to correctly set the value of cmd so that it both logs accurately and executes correctly and as intended, but I find it to be more trouble than it is worth. (However, I wait for someone to show how to do it easily; I know it involves printf and the %q specifier.)

chepner
  • 497,756
  • 71
  • 530
  • 681
0

set -x is good for debugging a script. When you just want to see your original command, use

set -v
lsuser -f root|grep -i maxage|awk -F= '{print$2}'
set +v
Walter A
  • 19,067
  • 2
  • 23
  • 43