Echo tab characters in bash script

后端 未结 10 2105
予麋鹿
予麋鹿 2020-12-07 08:09

How do I echo one or more tab characters using a bash script? When I run this code

res=\'       \'x # res = \"\\t\\tx\"
echo \'[\'$res\']\' # expect [\\t\\tx         


        
10条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 08:34

    Use the verbatim keystroke, ^V (CTRL+V, C-v, whatever).

    When you type ^V into the terminal (or in most Unix editors), the following character is taken verbatim. You can use this to type a literal tab character inside a string you are echoing.

    Something like the following works:

    echo "^V"     # CTRL+V, TAB
    

    Bash docs (q.v., "quoted-insert")

    quoted-insert (C-q, C-v) Add the next character that you type to the line verbatim. This is how to insert key sequences like C-q, for example.

    side note: according to this, ALT+TAB should do the same thing, but we've all bound that sequence to window switching so we can't use it

    tab-insert (M-TAB) Insert a tab character.

    --

    Note: you can use this strategy with all sorts of unusual characters. Like a carriage return:

    echo "^V^M"        # CTRL+V, CTRL+M
    

    This is because carriage return is ASCII 13, and M is the 13th letter of the alphabet, so when you type ^M, you get the 13th ASCII character. You can see it in action using ls^M, at an empty prompt, which will insert a carriage return, causing the prompt to act just like you hit return. When these characters are normally interpreted, verbatim gets you get the literal character.

提交回复
热议问题