Shell echo 命令

echo 的转义、-n 与 -e、颜色输出,以及为什么更推荐 printf。

Beginner
Key Pointsecho 默认加换行,-n 去掉换行,-e 才解析 \n 与 \t;跨平台脚本用 printf 更稳。

基本用法

Bash
echo "hello world"
echo -n "no newline"
echo " <- after"
Output
hello world
no newline <- after

转义

Bash
echo -e "line1\nline2"
echo -e "col1\tcol2"
echo -e "tab:\there"
Output
line1
line2
col1	col2
tab:	here
EscapeOutput
\nNewline
\tTab
\\Backslash
\cStop output (no trailing newline)

颜色

Bash
echo -e "\033[32mOK\033[0m"      # 绿色
echo -e "\033[31mFAIL\033[0m"    # 红色

\033[ starts an escape sequence: 32 is green, 31 red, \033[0m resets. Guard colour output with [ -t 1 ], otherwise redirected logs fill with escape codes.

echo 的可移植性问题

Bash
printf "name=%s age=%d\n" "Alice" 30
printf "%-8s|%8s|\n" "left" "right"
printf "%s\n" a b c
Output
name=Alice age=30
left    |   right|
a
b
c
echo -e behaves differently across dash, zsh and busybox, and echo "$var" treats a leading -n as a flag. Use printf when formatting matters.

Friends & Partners