为什么bash数组会忽略换行符?

时间:2012-11-15 11:19:10

标签: arrays bash

  

可能重复:
  Printf example in bash does not create a newline

我有一个示例脚本“array-test.sh”,它将三个函数聚合到一个数组中:

[user@host ~]$ cat array-test.sh 
#!/usr/bin/env bash

function1() {
   printf '%s\n\n\n' "cat" 
}

function2() {
   printf '%s\n\n\n' "dog" 
}

function3() {
   printf '%s\n\n\n' "mouse" 
}

for function in\
    function1\
    function2\
    function3; do
    array[$((index++))]=$($function)
done

echo "${array[@]}"
[user@host ~]$ ./array-test.sh 
cat dog mouse
[user@host ~]$ 

但是,缺少换行符。是什么导致了这种行为?

3 个答案:

答案 0 :(得分:2)

另一个选择:在字符串末尾添加一个字符(@)。字符串中间的换行符将保留在$( ... )中。然后,通过参数展开删除字符:

#!/bin/bash
function1() {
   printf '%s\n\n\n@' "cat" 
}

function2() {
   printf '%s\n\n\n@' "dog" 
}

function3() {
   printf '%s\n\n\n@' "mouse" 
}

for function in\
    function1\
    function2\
    function3; do
    array[index++]=$($function)
    array[index]=${array[index]%@}
done

echo "${array[@]}"

答案 1 :(得分:1)

如ÁlvaroG.Vicario所示,反引号(和$())删除尾随换行符。没有逃脱它,所以如果你必须,你将不得不解决它:

#!/usr/bin/env bash    

function1() {
   printf '%s' "cat"
}

function2() {
   printf '%s' "dog"
}

function3() {
   printf '%s' "mouse"
}

for function in\
    function1\
    function2\
    function3; do
    array[$((index++))]=$($function)
done

# manually add three newlines here
array=("${array[@]/%/$'\n'$'\n'$'\n'}")

echo "${array[@]}"

答案 2 :(得分:1)

似乎子shell扩展会切换换行符,但前提是它们最后会出现。这是一个kludge:

function3() {
   printf '%s\n\n\n-' "mouse" 
}

foo=$(function3)
foo=${foo%-}
echo "$foo"