如何在shell脚本中将包含空格的字符串添加到数组中

问题描述 投票:0回答:1

我尝试了一些方法在 shell 脚本中将包含空格的字符串添加到数组中,但失败了。

对于字符串变量,我可以轻松连接它们。

#!/usr/bin/env bash

str1="hello"
str2="world"
# ✅
strs="$str1 $str2"
# or ✅
# strs+="$str1 "
# strs+="$str2"
# or ✅
# strs="$str1 ""$str2"

echo $strs
# hello world

错误

但是当我向数组添加包含空格的字符串时,这不起作用。 它将字符串分成两个项目。

#!/usr/bin/env bash

str1="hello"
str2="world"
# ❌
# strs="$str1\ $str2"
# strs="$str1'\ '$str2"
strs="$str1 $str2"

arr=()
arr+=("$strs")

for item in ${arr[@]}; do
  echo "item = $item"
done
# item = hello
# item = world

尝试过

删除空格后,使用其他符号它可以工作,但不是预期的结果。

#!/usr/bin/env bash

str1="hello"
str2="world"
# ❓
# strs="$str1"-"$str2"
strs="$str1"_"$str2"

arr=()
arr+=("$strs")

for item in ${arr[@]}; do
  echo "item = $item"
done
# item = hello_world

那么,这有什么问题,以及如何解决它。

目标

我只想获取一项带有空格的项目。

#!/usr/bin/env bash

str1="hello"
str2="world"
# ❓
strs="string with whitespace"

arr=()
arr+=("$strs")

for item in ${arr[@]}; do
  echo "item = $item"
done
# ❓
# item = hello world
arrays linux bash shell whitespace
1个回答
0
投票
for item in ${arr[@]}; do

未加引号的扩展结果会进行分词。任何数组在这里都无效。引用扩展。

for item in "${arr[@]}"; do

使用 shellcheck 检查脚本以防止此类错误。

© www.soinside.com 2019 - 2024. All rights reserved.