With bash 4.1 or later:
bash
#!/bin/bashexec 5> command.txtBASH_XTRACEFD="5"echo -n "hello "set -xecho -n worldset +xecho "!"
Output to stdout (FD 1):
hello world!
Output to command.txt (FD 5):
+ echo -n world+ set +x