在bash中运行echo时,斜杠是目录错误

问题描述

每次终端加载时,我都尝试输出以下ascii字符:

   __  __                  _
  / / / /___  ____ _____ _(_)
 / / / / __ \/ __ / /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,_/\__,/_/
                 /____/

所以我在.bashrc的末尾添加了以下内容

echo "   __  __                  _ 
  / / / /___  ____ _____ _(_)
 / / / / __ \/ __ `/ __ `/ / 
/ /_/ / / / / /_/ / /_/ / /  
\____/_/ /_/\__,/_/   
                 /____/      "

它会打印:

enter image description here

似乎将ascii艺术中的斜杠误解为转义序列,这就是为什么它打印-bash: /: Is a directory的原因。我该如何摆脱呢?如果我向.bashrc添加了简单的内容,例如echo "Hello World!!",它不会显示错误消息。

解决方法

改为使用单引号:

echo \
'   __  __                  _ 
  / / / /___  ____ _____ _(_)
 / / / / __ \/ __ `/ __ `/ / 
/ /_/ / / / / /_/ / /_/ / /  
\____/_/ /_/\__,_/\__,/_/   
                 /____/      
'
,

尝试这样:

text=(
    '   __  __                  _'
    '  / / / /___  ____ _____ _(_)'
    ' / / / / __ \/ __ `/ __ `/ /'
    '/ /_/ / / / / /_/ / /_/ / /'
    '\____/_/ /_/\__,/_/'
    '                 /____/'
)

printf '%s\n' "${text[@]}"
,

对于多行文本文字,使用HereDoc非常合适:

# Use a quoted heredoc 'marker' to disable expansion of backticks
cat <<'LOGO'
   __  __                  _
  / / / /___  ____ _____ _(_)
 / / / / __ \/ __ `/ __ `/ /
/ /_/ / / / / /_/ / /_/ / /
\____/_/ /_/\__,/_/
                 /____/
LOGO

未引用heredoc标记:

cat <<EOF 
hello `echo world`
EOF

输出:

hello world

在heredoc标记为“标记”:

cat <<'EOF'
hello `echo world`
EOF

输出:

hello `echo world`