3

There is \t option for horizontal tab in echo

wolf@linux:~$ echo hello
hello
wolf@linux:~$ 

wolf@linux:~$ echo -e '\thello'
    hello
wolf@linux:~$ 

Is there any similar option in read?

wolf@linux:~$ read -p 'hello '
hello wolf
wolf@linux:~$ 
wolf@linux:~$ read -p '\thello '
\thello wolf
wolf@linux:~$ 

Desired Output

wolf@linux:~$ read -p '\thello ' <- need something to produce something like tab or `\t` in `echo`
    hello wolf
wolf@linux:~$ 
6

You can always use the ksh93-style $'...' form of quotes that understand those escape sequences:

IFS= read -r -p $'\thello ' var

(the IFS= and -r are not relevant, I'm just adding them here as calling read without them rarely makes sense).

Note that -p is not a standard sh function. In ksh/zsh, -p is to read from the co-process and prompts are specified with read 'var?Prompt: '. It's unfortunate that bash chose to introduce an incompatible API here. You don't have to use -p though, you can just do portably:

printf >&2 '\thello '
IFS= read -r var

printf does recognise those escape sequences in its format argument, and arguments for %b specifiers. Whether echo recognises them (or accepts a -e option to recognise them) depends on the implementation and for many implementations (including bash's builtin) on build time and runtime settings, so is best avoided.

| improve this answer | |
0

You could always simply add 8 spaces:

read -p '        hello '

But yes, you can also get an actual tab character:

read -p $'\t''hello '

Or

read -p "$(echo -e '\thello ')"

Or

read -p "$(printf '\thello ')"
| improve this answer | |
  • Why 4 spaces? TAB stops are generally 8 columns apart in terminals. – Stéphane Chazelas Oct 15 at 16:04
  • @StéphaneChazelas because that's the OP had. – terdon Oct 15 at 16:08
  • It looks more like it's how stackexchange renders tabs. It's actually really annoying as most terminals and web browsers do render them 8 columns apart, so when you're copy pasting a TAB from a terminal to the editing textarea when writing a SE post, it's fine, but when you post the article, the formatting is mangled. – Stéphane Chazelas Oct 15 at 16:13
  • @StéphaneChazelas eh, either way, the point was just that you can add N spaces and might not need a tab, specifically. I'm happy to change it to 8, if you prefer. – terdon Oct 15 at 16:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.