- How to debug a bash script?
- 8 Answers 8
- Using set -x
- log4bash
- log4sh
- How to Use GDB to Debug Programs in Ubuntu 20.04
- Prerequisites
- Installing Packages
- C-Program example for debugging
- Code
- Compile C Program using GCC
- Execute the test program
- Debugging an Application on Linux
- Initiate Debugger
- Debug Breakpoints
- Add Breakpoints
- Step through Breakpoints
- Information About Breakpoints
- Delete Breakpoints
- Watch Variables
- Quit Debugger
- Conclusion
- Search
- About This Site
- Latest Tutorials
- How Can I debug a C program on Linux?
- 4 Answers 4
- How to Debug a C or C++ Program on Linux Using gdb
How to debug a bash script?
I’m having some problems with some scripts in bash, about errors and unexpected behaviors. I would like to investigate the causes of the problems so I can apply fixes. Is there a way I can turn some kind of «debug-mode» for bash, to get more information?
8 Answers 8
Start your bash script with bash -x ./script.sh or add in your script set -x to see debug output.
Additional with bash 4.1 or later:
If you want to write the debug output to a separate file, add this to your script:
exec 5> debug_output.txt BASH_XTRACEFD="5"
If you want to see line numbers add this:
If you have access to logger command then you can use this to write debug output via your syslog with timestamp, script name and line number:
#!/bin/bash exec 5> >(logger -t $0) BASH_XTRACEFD="5" PS4='$LINENO: ' set -x # Place your code here
You can use option -p of logger command to set an individual facility and level to write output via local syslog to its own logfile.
-v can also help (prints out each line as they get executed. can be combined with -x). And see also : bashdb.sourceforge.net
@aggsol: If you use BASH_XTRACEFD=»5″ bash writes the trace output generated when set -x is enabled to file descriptor 5. exec 5> >(logger -t $0) redirects output from file descriptor 5 to logger command.
Using set -x
I always use set -x and set +x . You can wrap areas that you want to see what’s happening with them to turn verbosity up/down.
#!/bin/bash set -x ..code to debug. set +x
log4bash
Also if you’ve done development work and are familiar with the style of loggers that go by the names log4j, log4perl, etc., then you might want to make use of log4bash.
Let’s face it — plain old echo just doesn’t cut it. log4bash is an attempt to have better logging for Bash scripts (i.e. make logging in Bash suck less).
From there you can do things like this in your Bash scripts:
#!/usr/bin/env bash source log4bash.sh log "This is regular log message. log and log_info do the same thing"; log_warning "Luke . you turned off your targeting computer"; log_info "I have you now!"; log_success "You're all clear kid, now let's blow this thing and go home."; log_error "One thing's for sure, we're all gonna be a lot thinner."; # If you have figlet installed -- you'll see some big letters on the screen! log_captains "What was in the captain's toilet?"; # If you have the "say" command (e.g. on a Mac) log_speak "Resistance is futile";
Resulting in this type of output:
log4sh
If you need something more portable there’s also the older log4sh . Works similar to log4bash , available here:
How to Use GDB to Debug Programs in Ubuntu 20.04
GNU Debugger (GDB) is an open-source debugger for GNU Systems. The debugger is portable and can be used for multiple languages as C/C++ and Fortran. It can be used for debugging programs by observing their states on specific breakpoints and even altering the flow or values for further execution. Usually, the GDB runs in command-line but several GUI has been developed for it as well.
In this article, we explore how to debug C programs using GDB in Ubuntu 20.04 LTS (Focal Fossa).
Prerequisites
Note: The commands discussed in this article have been tested on Ubuntu 20.04 LTS (Focal Fossa).
Installing Packages
Install prerequisite GN packages for compiling and debugging. Run the following command in the terminal:
$ sudo apt install gcc gdb -y
C-Program example for debugging
Code
Before running, a program needs to be compiled. We are going to compile the following C code in the file main.c.
#include int main() < for (int i=0; ireturn 0; >
Compile C Program using GCC
Usually, a C code is compiled in GCC using the following command:
Another argument needs to be provided to include symbols in the binary. These symbols are used by GDB to track and debug the program. Run the following command in terminal to compile the C code:
An executable file named bin will appear.
Execute the test program
The binary file named bin can be executed like any other executable file on a command-line interface. Use the following command to run it in terminal:
The output of the code will appear.
Debugging an Application on Linux
Initiate Debugger
Run the GDB utility using following command in the terminal:
Press enter. The console for GDB terminal will appear. Enter the run command in this console to run the executable provided to the utility as an argument.
Debug Breakpoints
Add Breakpoints
Breakpoints can be added in several ways. We will be adding a breakpoint on the printf function in our code. Run the following command in terminal to add a breakpoint:
Alternatively, a line number can be used to add a breakpoint as well.
Enter the run command and the program will stop at the breakpoint.
Step through Breakpoints
Use the command continue to continue the execution of the program.
There are two other commands for different purposes of continuing the execution of the program:
- Step: steps through the next machine instruction.
- Next: steps to through the next line of code.
Abbreviations of commands can also be used. Like abbreviation of continue command is c.
Information About Breakpoints
Information about breakpoints can be observed using info command of gdb. Run the following command the terminal:
The information about breakpoints will appear.
Note: The number on the left of the breakpoint is used to refer to it by other commands.
Delete Breakpoints
A breakpoint can be deleted using the delete command and by referring to the breakpoint number observed in the output of the info utility.
Now the breakpoint has been deleted and if run, the program will execute straight to the end.
Watch Variables
Variables can be watched using the watch utility. First, we need to enter the scope in which the variable exists. For this purpose, add a breakpoint first using the following command:
Then run the code that hits this breakpoint.
Now we are in the loop where the variable i exists.
The watch command will be used to observe the previous and new value of the variable i in the loop.
Now the breakpoint generated by watch command will appear in the list of breakpoints as well. The list of breakpoints can be shown using the following command:
Moreover, we do not need the breakpoint inserted earlier. It can be easily removed using the following command:
Now if continued, the code will view values whenever the variable has changed the value and show both old and new values.
Further iterations of the program can be observed as well, using the same command.
Quit Debugger
Run the following command in the terminal to exit the debugger.
This close gdb utility and the default command-line prompt will appear.
Conclusion
In this article, we explored how to run and break a program in GDB. Moreover, it was also configured to break itself when the value of a variable has changed. We hope you can easily debug your programs in GDB after following this article.
Search
About This Site
Vitux.com aims to become a Linux compendium with lots of unique and up to date tutorials.
Latest Tutorials
How Can I debug a C program on Linux?
I am writing a C language program on Linux and compiling it using GCC. I also use a Make file. I want to debug my program. I don’t want to debug a single file, I want to debug the whole program. How can I do it?
4 Answers 4
Compile your code with the -g flag, and then use the gdb debugger. Documentation for gdb is here, but in essence:
gcc -g -o prog myfile.c another.c
If you want a user-friendly GUI for gdb, take a look at DDD or Insight.
There’s also a graphical interface for gdb named ddd that can be useful if you’re having a hard time with getting used to gdb.
I guess that you are building from the command line.
You might want to consider an IDE (Integrated Development Environment), such as KDevelop or Eclipse, etc (hint — Eclipse . ECLPISE . E C L I PS E).
Use an IDE to edit your code, refactor your code, examine your code — class tree, click a variable, class or function to jump to declaration, etc, etc
- run your code in the IDE
- set breakpoints to stop at particular lines
- or just step through, a line at a time
- examine the call stack to see how you go there
- examine the current values of variables, to understand your problem
- change the values of those variables and run to see what happens
- and more, more, more
p.s as wasatz mentioned- DDD is great — for visualizing the contents of arrays/matrices, and — imo — especially if you have linked lists
How to Debug a C or C++ Program on Linux Using gdb
The normal process for developing computer programs goes something like this: write some code, compile the code, run the program. If the program does not work as expected, then you go back to the code to look for errors (bugs) and repeat the cycle again.
Depending on the complexity of the program and the nature of the bugs, there are times when you can do with some additional help in tracking down the errors. This is what a “debugger” does. It allows you to examine a computer program while it is running. You can see the values of the different variables, you can examine the contents of memory and you can halt the program at a specified point and step through the code one line at a time.
The primary debugger on Linux is the GNU debugger (gdb). It might already be installed on your system (or a slimmed down version called gdb-minimal), but to be sure type the following command in a terminal:
To use the debugger, you need to tell the compiler to include debug information in the binary. Create a file called “hello10.c” using nano:
Copy and paste in the following code:
#include main() { int i; for(i=0;i10;i++) printf("%d",i); }
The «-g» flag tells the compiler to produce debug information, so to compile the program use:
To start debugging the program type:
At this point if you just start running the program (using the «run» command), then the program will execute and finish before you get a chance to do anything. To stop that, you need to create a «breakpoint» which will halt the program at a specified point. The easiest way to do this is to tell the debugger to stop in the function «main()»:
The debugger has stopped at the first executable line of code, e.g. the «for» loop. To step to the next line, type «next» or «n» for short. Keep using «next» to repeat around the loop a couple of times:
To inspect the value of a variable use the «print» command. In our example program, we can examine the contents of the variable «i»:
Repeat around the loop and few more times and see how «i» changes:
next next next next print i
In the example above «i» has reached the value of 4. The loop will continue while «i» is less than 10. You can change the value of a variable using «set var.» Type the following in gdb to set «i» to 10.
set var i = 10 print i next
You may need to do another «next» (depending on where the program was halted when you set «i» to 10), but when the «for» loop line is next executed, the loop will exit, because «i» is no longer less than 10.
The «next» command doesn’t drill down into functions but rather the function is executed, and the debugger stops again at the next line after the function. If you want to step into a function, use the «step» command, or «s» for short.
Another way to debug your program is to set a watch on a variable. What this does is halt the program whenever the variable changes. Restart the program again by typing «run.» Since the program is already running, the debugger will ask if you want to start it again from the beginning.
The program will stop in main (as we didn’t remove the break point). Now set a watch on «i»:
The «continue» command starts the program running again until the next break point condition. In this case it will run again until the variable «i» changes (due to the watch).
To stop debugging, just use the «quit» command.
If you want to learn some more about gdb, then a good place to start is the GDB Documentation. If you have any trouble with the examples given above, please use the comments section below and we will see if we can help.
Gary has been a technical writer, author and blogger since 2003. He is an expert in open source systems (including Linux), system administration, system security and networking protocols. He also knows several programming languages, as he was previously a software engineer for 10 years. He has a Bachelor of Science in business information systems from a UK University.
Our latest tutorials delivered straight to your inbox