HomeLinuxHow To Echo Shell Instructions as They Are Executed in Bash

How To Echo Shell Instructions as They Are Executed in Bash


Echoing shell instructions as they’re executed is a helpful approach of debugging shell scripts. It may possibly provide help to determine errors and perceive how your code is working. This text will talk about alternative ways to echo shell instructions as they’re executed and supply full Bash code for every methodology.

How To Echo Shell Instructions as They Are Executed in Bash

Echoing instructions in Bash assist customers and builders perceive what is occurring of their scripts. By displaying the instructions as they’re executed, customers can confirm that the script is working as meant and determine any errors or surprising habits, listed here are some methods to echo shell instructions in Bash:

Methodology 1: Utilizing set Command

The set command in Bash can be utilized to allow or disable choices and set shell parameters. By setting the -x choice, you’ll be able to allow shell tracing, which is able to trigger Bash to print every command earlier than it’s executed.

#!/bin/bash

set -x

echo “Whats up, Linux!”

set +x

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

Graphical user interface, text Description automatically generated

Methodology 2: Utilizing the DEBUG lure

The DEBUG lure is a particular shell lure that’s executed earlier than every command in a Bash script. By defining a perform for the DEBUG lure, you’ll be able to print every command earlier than it’s executed:

#!/bin/bash

perform debug {

echo $BASH_COMMAND

}

lure debug DEBUG

echo “Whats up, world!”

lure – DEBUG

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

Graphical user interface, text Description automatically generated

Methodology 3: Utilizing the Bash -x choice

You may also allow xtrace mode by passing the -x choice to the Bash command when executing a script. For instance using -x choice right here is an easy Bash script that simply prints a string utilizing the echo command:

#!/bin/bash

echo “Whats up, Linux!”

To execute this script with xtrace mode enabled, you’ll be able to run the script utilizing the under given syntax:

bash -x <scipt-file-name>

On this instance, the Bash -x command executes the script with xtrace mode enabled, inflicting the shell to print every command earlier than it’s executed. The echo command then prints “Whats up, world!” to the console:

Conclusion

Echoing shell instructions as they’re executed is a robust method to debug Bash scripts. By utilizing the set command, the -x choice and the DEBUG lure, you’ll be able to simply print every command earlier than it’s executed.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments