我希望能够做这样的事情
VAR='\\'
echo "$VAR"
并得到结果
\\
我实际得到的结果是
\
实际上,我有一个很长的字符串,其中有许多 \\ ,当我打印它时,bash 会删除第一个 \ 。
答案1
对于用于逐字输出给定字符串并后跟换行符的bash
内置命令,您需要:echo
# switch from PWB/USG/XPG/SYSV-style of echo to BSD/Unix-V8-style of echo
# where -n/-e options are recognised and backslash sequences not enabled by
# default
shopt -u xpg_echo
# Use -n (skip adding a newline) with $'\n' (add a newline by hand) to make
# sure the contents of `$VAR` is not treated as an option if it starts with -
echo -n "$VAR"$'\n'
或者:
# disable POSIX mode so options are recognised even if xpg_echo is also on:
set +o posix
# use -E to disable escape processing, and we use -n (skip adding a newline)
# with $'\n' (add a newline by hand) to make sure the contents of `$VAR` is not
# treated as an option if it starts with -
echo -En "$VAR"$'\n'
这些是特定于bash
shell 的,您需要针对其他 shell 采取不同的方法echo
,并注意某些实现不会让您输出任意字符串。
但这里最好是使用printf
标准命令:
printf '%s\n' "$VAR"
看为什么 printf 比 echo 更好?了解详情。
答案2
使用 4 个反斜杠而不是 2 个