Hack 32. PS4 – Used by “set -x” to prefix tracing output

by Ramesh

The PS4 shell variable defines the prompt that gets displayed, when you execute a shell script in debug mode as shown below.

Shell script and output WITHOUT PS4:

  1. ramesh@dev-db ~> cat ps4.sh
  2.  
  3. set -x
  4. echo "PS4 demo script"
  5. ls -l /etc/ | wc -l
  6. du -sh ~
  7.  
  8. ramesh@dev-db ~> ./ps4.sh
  9. ++ echo 'PS4 demo script'
  10. PS4 demo script
  11. ++ ls -l /etc/
  12. ++ wc -l
  13. 243
  14. ++ du -sh /home/ramesh
  15. 48K /home/ramesh
  16.  
  17. [Note: This displays the default "++" while tracing the output using set -x]

Shell script and output WITH PS4:

The PS4 defined below in the ps4.sh has the following two codes:

  • $0 – indicates the name of script
  • $LINENO – displays the current line number within the script
  1. ramesh@dev-db ~> cat ps4.sh
  2.  
  3. export PS4='$0.$LINENO+ '
  4. set -x
  5. echo "PS4 demo script"
  6. ls -l /etc/ | wc -l
  7. du -sh ~
  8.  
  9. ramesh@dev-db ~> ./ps4.sh
  10. ../ps4.sh.3+ echo 'PS4 demo script'
  11. PS4 demo script
  12. ../ps4.sh.4+ ls -l /etc/
  13. ../ps4.sh.4+ wc -l
  14. 243
  15. ../ps4.sh.5+ du -sh /home/ramesh
  16. 48K /home/ramesh
  17.  
  18. [Note: This displays the modified "{script-name}.{line-number}+" while tracing the output using set -x]