Echo some command lines in a shell script (echo on for single command)

Den picture Den · Oct 4, 2012 · Viewed 8.2k times · Source

In shell scripts I would like to echo some of the major (long running) commands for status and debug reason. I know I can enable an echo for all commands with set -x or set -v. But I don't want to see all the commands (specially not the echo commands). Is there a way to turn on the echo for just one command?

I could do like this, but that's ugly and echoes the line set +x as well:

#!/bin/sh

dir=/tmp
echo List $dir

set -x
ls $dir
set +x

echo Done!

Is there a better way to do this?

Answer

Jonathan Leffler picture Jonathan Leffler · Oct 4, 2012

At the cost of a process per occasion, you can use:

(set -x; ls $dir)

This runs the command in a sub-shell, so the set -x only affects what's inside the parentheses. You don't need to code or see the set +x. I use this when I need to do selective tracing.