Search⌘ K
AI Features

Debugging

Explore key Bash debugging techniques including syntax checking with the -n flag, job control signals, managing script variables safely, and profiling scripts with the xtrace option. Understand how to use shellcheck for script analysis and improvement. This lesson equips you to debug and enhance Bash scripts effectively.

How Important is this Lesson?

If you write, use or maintain bash of any complexity you’ll want to know how to debug it!

Syntax Checking Options

Start by creating this simple (but broken) script:

Shell
cat > debug_script.sh << 'END'
#!/bin/bash
A=some value
echo "${A}
echo "${B}"
END
Terminal 1
Terminal
Loading...

Now run it with the -n flag. This flag only parses the script, rather than running it. It’s useful for detecting basic syntax errors.

Shell
bash -n debug_script.sh

You can see it’s broken. Fix it. Then run it:

Shell
bash debug_script.sh

You’ll see:

    [1]+  Done                    sleep 60

in the terminal.

Again, it reports the job number, this time with the status (Done), and the command that was originally run (sleep 60).

Controlling Jobs

Just like starting jobs, you can control jobs by sending signals to them.

Here you’re going to start two jobs, one to sleep for two minutes, and the next for one second more (so we can distinguish between them).

Shell
bash -v debug_script.sh

Try tracing to see more details about what’s going on. Each statement gets a new line.

Shell
bash -x debug_script.sh

Using these flags together can help debug scripts ...