Simple method of bash script step debugging

By | June 19, 2022

I always wanted to be able to debug bash scripts just like any other code and I did not know how to do in for very long time.
However it is easy to do using trap command which may intercept different kind of signals and exceptions. Adding trap
in some place of your script you will force step by step script execution, press Enter to execute single script line or Ctrl/C to interrupt. This line is:
trap ‘echo “# $BASH_COMMAND”;read’ DEBUG
If your script is using function it is necessary to add this trap line in the beginning of the function code to step inside.
There is modified get_xml_node_value.sh script with trap command from “Bash script for xml parsing” post:


#! /bin/bash
get_xml_node_value()
{
  trap 'echo "# $BASH_COMMAND";read' DEBUG
  startline=$(grep -n "<$2" $1 | cut -d':' -f1)
  lastline=$(grep -n "<\/$2>" $1 | cut -d':' -f1)
  value=$(sed -n $startline,$lastline'p' $1)
  value=$(echo $value | sed -e "s/^.*<$3/<$3/" | sed -e "s/<$3>//g" | sed -e "s/<\/$3>//g" | awk -F"<" '{print $1}' | sed -e 's/[[:space:]]*$//' )
}
trap 'echo "# $BASH_COMMAND";read' DEBUG
if [ $# -eq 3 ]; then
  if [ -f $1 ]; then
    get_xml_node_value $1 "$2" "$3"
    echo $value
  else
    echo "File $1 not found"
  fi
else
  echo "3 arguments are required: xml file name, section name, node name"
  echo "Example:"
  echo "./get_xml_node_value abc.xml \"Customer 1\" \"First name\""
fi

Step by step debugging of get_xml_node_value.sh script, parsing of “abc.xml file:


# ./get_xml_node_value.sh abc.xml "Customer 1" "First name"
# [ $# -eq 3 ]

# [ -f $1 ]

# get_xml_node_value $1 "$2" "$3"

# startline=$(grep -n "<$2" $1 | cut -d':' -f1)

# lastline=$(grep -n "<\/$2>" $1 | cut -d':' -f1)

# value=$(sed -n $startline,$lastline'p' $1)

# value=$(echo $value | sed -e "s/^.*<$3/<$3/" | sed -e "s/<$3>//g" | sed -e "s/<\/$3>//g" | awk -F"<" '{print $1}' | sed -e 's/[[:space:]]*$//' )

# echo $value

Jesus

#

Leave a Reply

Your email address will not be published. Required fields are marked *