Bash 数组中的字符串缺少空格

Bash 数组中的字符串缺少空格

我发现了一个奇怪的事情,如果有人能帮忙解决它会很好。

#!/bin/bash
#

dockerdir="docker"


step_1=("nginx" "create" "default.conf")
step_2=("nginx" "use" "default.conf" "replace" "server               tplphp:9000" "server      bbaphp1:9000;")
#step_3=("nginx" "use" "default.conf" "add" " server  bbaphp1:9000" " server  bbaphp2:9000")
#step_4=("nginx" "use" "default.conf" "add" "server  bbaphp2:9000" "server  bbaphp3:9000")
#step_5=("nginx" "use" "default.conf" "delete" " server  bbaphp3:9000")
#step_6=("php" "value0")
#step_7=("php" "value1")


declare -a buildfolders=(
  step_1[@]
  step_2[@]
)

#

echo "Start:"
     arrayleght=${#buildfolders[@]}
     for (( i=1; i<${arrayleght}+1; i++ ));
     do
       folder=${!buildfolders[$i-1]:0:1}
       file_task=${!buildfolders[$i-1]:1:1}
       file=${!buildfolders[$i-1]:2:1}
       task=${!buildfolders[$i-1]:3:1}
       variable_name=${!buildfolders[$i-1]:4:1}
       variable_value=${!buildfolders[$i-1]:5:1}
       echo "Folder ${folder} "
       #" leght "${#folder}
       echo "Task ${file_task}"
       # " leght "${#file_task}
       echo "File ${file}"
       # " leght "${#file}
       echo "Task for file ${task}"
       # " leght "${#task}
       echo "Variable name ${variable_name}"
       # " leght "${#variable_name}
       echo "Variable value ${variable_value}"
       # " leght "${#variable_value}
       echo " "
#  filemanipulations ./${dockerdir}/${folder}/ ${file_task} ${file} ${task} "${variable_name}" "${variable_value}"
     done

echo "Done."

结果是:

Start:
Folder nginx 
Task create
File default.conf
Task for file 
Variable name 
Variable value 

Folder nginx 
Task use
File default.conf
Task for file replace
Variable name server tplphp:9000
Variable value server bbaphp1:9000;

Done.

问题:空格在哪里?将结果与输入进行比较:

step_2=("nginx" "use" "default.conf" "replace" "server               tplphp:9000" "server      bbaphp1:9000;")

仅剩一个空位。

答案1

问题在于 Bash shell 的字段拆分功能会删除多个空格。您可以通过引用所有变量/数组扩展来防止这种情况。当您构建复合数组时:

declare -a buildfolders=(
  "${step_1[@]}"
  "${step_2[@]}"
)

另外,当您将该数组的各部分放入变量时:

echo "Start:"
     arrayleght=${#buildfolders[@]}
     for (( i=1; i<${arrayleght}+1; i++ ));
     do
       folder="${!buildfolders[$i-1]:0:1}"
       file_task="${!buildfolders[$i-1]:1:1}"
       file="${!buildfolders[$i-1]:2:1}"
       task="${!buildfolders[$i-1]:3:1}"
       variable_name="${!buildfolders[$i-1]:4:1}"
       variable_value="${!buildfolders[$i-1]:5:1}"

这将使所有多个空间保持在原位。

相关内容