BASH Programming

How To Echo Shell Commands as They Are Executed in Bash

Echoing shell commands as they are executed is a useful way of debugging shell scripts. It can help you identify errors and understand how your code is working. This article will discuss different ways to echo shell commands as they are executed and provide full Bash code for each method.

How To Echo Shell Commands as They Are Executed in Bash

Echoing commands in Bash help users and developers understand what is happening in their scripts. By displaying the commands as they are executed, users can verify that the script is working as intended and identify any errors or unexpected behavior, here are some ways to echo shell commands in Bash:

Method 1: Using set Command

The set command in Bash can be used to enable or disable options and set shell parameters. By setting the -x option, you can enable shell tracing, which will cause Bash to print each command before it is executed.

#!/bin/bash

set -x

echo "Hello, Linux!"

set +x

The output of this script will include the command being executed:

Graphical user interface, text Description automatically generated

Method 2: Using the DEBUG trap

The DEBUG trap is a special shell trap that is executed before each command in a Bash script. By defining a function for the DEBUG trap, you can print each command before it is executed:

#!/bin/bash

function debug {

echo "$BASH_COMMAND"

}

trap debug DEBUG

echo "Hello, world!"

trap - DEBUG

The output of this script will include the command being executed:

Graphical user interface, text Description automatically generated

Method 3: Using the Bash -x option

You can also enable xtrace mode by passing the -x option to the Bash command when executing a script. To illustrate the use of -x option here is a simple Bash script that just prints a string using the echo command:

#!/bin/bash

echo "Hello, Linux!"

To execute this script with xtrace mode enabled, you can run the script using the below given syntax:

bash -x <scipt-file-name>

In this example, the Bash -x command executes the script with xtrace mode enabled, causing the shell to print each command before it is executed. The echo command then prints “Hello, world!” to the console:

Conclusion

Echoing shell commands as they are executed is a powerful way to debug Bash scripts. By using the set command, the -x option and the DEBUG trap, you can easily print each command before it is executed.

About the author

Aaliyan Javaid

I am an electrical engineer and a technical blogger. My keen interest in embedded systems has led me to write and share my knowledge about them.