如何使用bash脚本回显一个或多个制表符? 当我运行这段代码时

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

我明白了

res=[ x] # that is [<space>x]

当前回答

从bash手册页:

形式为$'string'的单词被特殊处理。单词扩展为字符串,反斜杠转义字符替换为ANSI C标准指定的字符。

所以你可以这样做:

echo $'hello\tworld'

其他回答

你需要为echo使用-e标志

echo -e "\t\t x"
echo -e ' \t '

将回显'space制表符换行符' (-e表示'启用反斜杠转义'):

$ echo -e ' \t ' | hexdump -C
00000000  20 09 20 0a                                       | . .|

把你的字符串放在双引号之间:

echo "[$res]"

从bash手册页:

形式为$'string'的单词被特殊处理。单词扩展为字符串,反斜杠转义字符替换为ANSI C标准指定的字符。

所以你可以这样做:

echo $'hello\tworld'
res="\t\tx"
echo -e "[${res}]"