var="a b c"
for i in $var
do
p="$p
$i" # New line directly in the source code
done
echo "$p" # Double quotes required
# But -e not required
避免额外的引导换行
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is Bash specific
p="$i" || # First -> Set
p="$p
$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
使用函数
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p
$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
var="a b c"
for i in $var
do
p="$p"$'\n'"$i"
done
echo "$p" # Double quotes required
# But -e not required
避免额外的引导换行
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p"$'\n'"$i" # After -> Append
unset first_loop
done
echo "$p" # No need -e
使用函数
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p"$'\n'"$i" # Append
done
echo "$p" # No need -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
使用 echo -e将 \n转换为新行
p="${var1}\n${var2}"
echo -e "${p}"
echo -e将这两个字符 "\n"解释为一个新行。
var="a b c"
first_loop=true
for i in $var
do
p="$p\n$i" # Append
unset first_loop
done
echo -e "$p" # Use -e
避免额外的引导换行
var="a b c"
first_loop=1
for i in $var
do
(( $first_loop )) && # "((...))" is bash specific
p="$i" || # First -> Set
p="$p\n$i" # After -> Append
unset first_loop
done
echo -e "$p" # Use -e
使用函数
embed_newline()
{
local p="$1"
shift
for i in "$@"
do
p="$p\n$i" # Append
done
echo -e "$p" # Use -e
}
var="a b c"
p=$( embed_newline $var ) # Do not use double quotes "$var"
echo "$p"
该行由 shell 解析并展开为“ var = “ anewlinebnewlinec”,这正是我们希望变量 var 成为的样子。这将 没有工作在较旧的 shell 上。
2. 使用 shell 扩展。
它基本上是一个包含多个命令的命令扩展:
Echo-E
var="$( echo -e "a\nb\nc" )"
Bash 和 Z shell < em > printf’% b’
var="$( printf '%b' "a\nb\nc" )"
Bash < em > printf-v
printf -v var '%b' "a\nb\nc"
简单的 打印(适用于大多数 shell) :
var="$( printf 'a\nb\nc' )"
3. 使用 shell 执行。
如果变量包含特殊字符,则可以使用第二个选项中列出的所有命令展开该变量的值。
因此,我们需要做的就是在变量中获取这些值,然后执行一些命令来显示:
var="a\nb\nc" # var will contain the characters \n not a newline.
echo -e "$var" # use echo.
printf "%b" "$var" # use bash %b in printf.
printf "$var" # use plain printf.