Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Capture -x debug commands into a file in Bash

Tags:

bash

debugging

Using set -x in bash prints the shell-expanded commands to stderr. I would like to redirect these to a file or pipe. But not the whole output - only some commands. Something like:

set -x command.txt  ### <-- command.txt param is made up
echo $A $B
set +x

This would put the debug output to command. txt.

Can this be done?

like image 580
Ondra Žižka Avatar asked Aug 31 '14 14:08

Ondra Žižka


People also ask

How do I save a bash output to a file?

To use bash redirection, you run a command, specify the > or >> operator, and then provide the path of a file you want the output redirected to. > redirects the output of a command to a file, replacing the existing contents of the file.

How do I debug a file in bash?

The debugging options available in the Bash shell can be switched on and off in multiple ways. Within scripts, we can either use the set command or add an option to the shebang line. However, another approach is to explicitly specify the debugging options in the command-line while executing the script.

How do I copy terminal output to a file?

the shortcut is Ctrl + Shift + S ; it allows the output to be saved as a text file, or as HTML including colors!

How do you save the output of a command to a file in Linux?

Method 1: Use redirection to save command output to file in Linux. You can use redirection in Linux for this purpose. With redirection operator, instead of showing the output on the screen, it goes to the provided file. The > redirects the command output to a file replacing any existing content on the file.


1 Answers

With bash 4.1 or later:

#!/bin/bash

exec 5> command.txt
BASH_XTRACEFD="5"

echo -n "hello "

set -x
echo -n world
set +x

echo "!"

Output to stdout (FD 1):

hello world!

Output to command.txt (FD 5):

+ echo -n world
+ set +x
like image 143
Cyrus Avatar answered Oct 19 '22 19:10

Cyrus