Shell echo 命令
echo 的转义、-n 与 -e、颜色输出,以及为什么更推荐 printf。
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| Escape | Output |
|---|---|
\n | Newline |
\t | Tab |
\\ | Backslash |
\c | Stop 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 cOutput
name=Alice age=30
left | right|
a
b
cecho -e behaves differently across dash, zsh and busybox, and echo "$var" treats a leading -n as a flag. Use printf when formatting matters.基本用法
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| 转义 | 输出 |
|---|---|
\n | 换行 |
\t | 制表符 |
\\ | 反斜杠 |
\c | 停止输出,不换行 |
颜色
Bash
echo -e "\033[32mOK\033[0m" # 绿色
echo -e "\033[31mFAIL\033[0m" # 红色\033[ 开始一段控制序列,32 是绿色、31 是红色,\033[0m 复位。写日志时用颜色要判断 [ -t 1 ],重定向到文件时颜色码会变成乱码。
echo 的可移植性问题
Bash
printf "name=%s age=%d\n" "Alice" 30
printf "%-8s|%8s|\n" "left" "right"
printf "%s\n" a b cOutput
name=Alice age=30
left | right|
a
b
cecho -e 在不同 shell(dash、zsh、busybox)行为不一致,echo "$var" 遇到 -n 开头的变量还会被当成选项。脚本里需要精确控制格式就用 printf。