Unix: Debugging your scripts even more effectively

Last week's post provided some tips and tricks for debugging scripts. This week's provides some even better ones!

By  

If you set your PS4 variable like this, you will see your script name, line number and, if applicable, your function name when you are debugging your script.

$ export 'PS4=+${BASH_SOURCE}:${LINENO}:${FUNCNAME[0]}: '

Here's a sample script:

#!/bin/bash

function quit {
    exit
}
function greet {
    echo Hello, $USER!
}
greet
quit

Here we run the script in debug mode:

$ bash -x foo
+:96:: bash -x foo
+foo:9:: greet
+foo:7:greet: echo Hello, 'shs!'
Hello, shs!
+foo:10:: quit
+foo:4:quit: exit

PS4 settings provide a lot more context for your debugging efforts. And you can make the output even more interesting if you like. My Internet rambling friend, Sandwich Maker, suggests these settings to put your script name in bold and underline your line numbers:

export BOLD=$(tput bold) SMUL=$(tput smul) SGR0=$(tput sgr0)
PS4="${BOLD}${0##*/}${SGR0} line ${SMUL}${LINENO}${SGR0}:\t"

Thanks to Sandwich Maker (Andrew Hay), Len Weisberg and JuzJoe for sharing their insights on debugging.

Photo Credit: 

flickr / louento.pix

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Operating SystemsWhite Papers & Webcasts

See more White Papers | Webcasts

Answers - Powered by ITworld

ITworld Answers helps you solve problems and share expertise. Ask a question or take a crack at answering the new questions below.

Join us:
Facebook

Twitter

Pinterest

Tumblr

LinkedIn

Google+

Ask a Question