如何在bash中从数组中打印字符串?

时间:2018-02-27 20:55:15

标签: bash

给出以下数组:

arr=("hello hello" "bye bye")

如何将arr中的任何元素打印到标准输出?

我试着通过下一个方式来做:

for line in ${arr[*]}; do
    echo ${line}
done

但在这种状态下,输出是:
你好
你好
再见
再见

我想得到:
你好,你好 再见

2 个答案:

答案 0 :(得分:1)

您刚刚遇到shell word splitting

如果你引用(就像你应该的那样),一切都可以:

$ for line in "${arr[@]}"; do echo "$line"; done

可以只是(don't read lines with for):

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

输出:

hello hello
bye bye

"双引号"每个包含空格/元字符和每个扩展的文字:"$var""$(command "$var")""${array[@]}""a & b"。使用'single quotes'代码或文字$'s: 'Costs $5 US'ssh host 'echo "$HOSTNAME"'。见
http://mywiki.wooledge.org/Quotes
http://mywiki.wooledge.org/Arguments
http://wiki.bash-hackers.org/syntax/words

$@$*"$@"(引用)之间的差异会扩展为每个位置参数作为其自己的参数:"$1" "$2" ... "$*"扩展为单个参数"$1c$2c...",其中cIFS的第一个字符。不带引号的$*$@undefined; 请勿使用。你几乎总是想要"$@"数组也是如此"${array[@]}"

答案 1 :(得分:0)

我认为它应该是:

function setAndCopy(sheetName){
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  sheet.getRange("B3:P").clearContent();
  var targetCell = sheet.getRange("B3");
  var formulaString = "=query(Vehicles!A2:AM,\"Select A,B,C,D,E,K where E<>''\")";

  targetCell.setFormula(formulaString);

  SpreadsheetApp.flush();

  Utilities.sleep(10000);

  sheet.getRange("B3:P").copyTo(sheet.getRange("B3:P"),{contentsOnly:true});
}

bash正试图做到最好解释。