我尝试了一些方法在 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
for item in ${arr[@]}; do
未加引号的扩展结果会进行分词。任何数组在这里都无效。引用扩展。
for item in "${arr[@]}"; do
使用 shellcheck 检查脚本以防止此类错误。