How to Use Special Characters with `read` Command in Bash

The aim of this pageđź“ť is to explain handling special characters, including newline characters, in the prompt string for the read command in Bash based on the particular example of modifying the prompt for user input.

Pavol Kutaj
1 min readApr 3, 2024
  • Initially attempted to hardcode a special character, like a newline, directly into a read command simply with double quotes — not working.
  • Discovered the solution of using ANSI-C quoting with $'...' syntax to directly insert escape sequences like newline characters in the prompt string for the read command.

code

  • initially attempted code which printed everything
read -p "\nthe enemy, the way, the end...(o?)" ordo
# >>> \nthe enemy, the way, the end...(o?)
  • a more complicated solution using ansi-c quoting:
read -p $'\n'"the enemy, the way, the end...(o?)" ordo

#
# the enemy, the way, the end...(o?)
  • simplified solution using $'...' syntax directly in the read command:
read -p $'the enemy, the way, the end...(o?)\n' ordo
#
# the enemy, the way, the end...(o?)
\n  : Newline
\t : Horizontal tab
\r : Carriage return
\\ : Backslash
\" : Double quote
\' : Single quote
\a : Alert (bell)
\b : Backspace
\f : Form feed
\v : Vertical tab

LINKS

--

--

Pavol Kutaj
Pavol Kutaj

Written by Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com

No responses yet