Skip to content

Latest commit

 

History

History
115 lines (68 loc) · 2.8 KB

01.Using_echo_and_printf_for_debugging.md

File metadata and controls

115 lines (68 loc) · 2.8 KB

Using echo and printf for Debugging in Linux Scripting

Debugging is a crucial part of scripting, helping you identify issues and understand the flow of your code. In Linux scripting, the echo and printf commands are commonly used for debugging purposes. This tutorial will guide you through the effective use of echo and printf to debug your scripts.

Using echo for Debugging

Basic Usage

The echo command is a simple way to print messages to the terminal, providing insights into the script's execution:

#!/bin/bash

echo "Script started."

This will print "Script started." when the script is executed.

Printing Variable Values

You can use echo to display the values of variables during runtime:

#!/bin/bash

name="Pavankumar"
echo "Hello, $name!"

This will print "Hello, John!" to the terminal.

Verbose Output

Adding descriptive messages to your script using echo can help trace the execution flow:

#!/bin/bash

echo "Initializing script..."
# Rest of the script
echo "Script completed successfully."

This provides a clear indication of different stages in your script.

Debugging Conditional Statements

You can use echo within conditional statements to understand the logic:

#!/bin/bash

number=10

if [ $number -gt 5 ]; then
    echo "Number is greater than 5."
else
    echo "Number is less than or equal to 5."
fi

This helps identify which branch of the conditional statement is executed.

Using printf for Debugging

Basic Usage

The printf command provides more advanced formatting capabilities than echo:

#!/bin/bash

printf "This is a formatted message: %s\n" "Hello, World!"

This will print a formatted message with "Hello, World!".

Formatting Variables

You can use placeholders in printf to format variable values:

#!/bin/bash

name="Pavankumar"
age=25

printf "Name: %s\nAge: %d\n" "$name" $age

This will print formatted information about the name and age variables.

Formatting Floating-Point Numbers

printf is useful for formatting floating-point numbers with precision:

#!/bin/bash

pi=3.14159

printf "Value of pi: %.2f\n" $pi

This will print the value of pi with two decimal places.

Conclusion

Using echo and printf for debugging in Linux scripting is a practical and effective approach. These commands help you gain insights into the execution flow, display variable values, and format output for better readability. Experiment with different use cases to become proficient in leveraging echo and printf as valuable debugging tools in your Linux scripts.