Hack 31. PS3 – Prompt used by “select” inside shell script

by Ramesh

You can define a custom prompt for the select loop inside a shell script, using the PS3 environment variable, as explained below.

Shell script and output WITHOUT PS3:

  1. ramesh@dev-db ~> cat ps3.sh
  2. select i in mon tue wed exit
  3. do
  4. case $i in
  5. mon) echo "Monday";;
  6. tue) echo "Tuesday";;
  7. wed) echo "Wednesday";;
  8. exit) exit;;
  9. esac
  10. done
  11.  
  12. ramesh@dev-db ~> ./ps3.sh
  13. 1) mon
  14. 2) tue
  15. 3) wed
  16. 4) exit
  17. #? 1
  18. Monday
  19. #? 4
  20.  
  21. [Note: This displays the default "#?" for select command prompt]

Shell script and output WITH PS3:

  1. ramesh@dev-db ~> cat ps3.sh
  2. PS3="Select a day (1-4): "
  3. select i in mon tue wed exit
  4. do
  5. case $i in
  6. mon) echo "Monday";;
  7. tue) echo "Tuesday";;
  8. wed) echo "Wednesday";;
  9. exit) exit;;
  10. esac
  11. done
  12.  
  13. ramesh@dev-db ~> ./ps3.sh
  14. 1) mon
  15. 2) tue
  16. 3) wed
  17. 4) exit
  18. Select a day (1-4): 1
  19. Monday
  20. Select a day (1-4): 4
  21.  
  22. [Note: This displays the modified "Select a day (1-4):" for select command prompt]