如何创建一个可以从数组中提取字符串的 bash 脚本?

如何创建一个可以从数组中提取字符串的 bash 脚本?

我有一个困境,我正在尝试编写一个 Linux bash 脚本,以便它从数组中提取每个字符串,并处理结果。

IE

var=("string one" "string two" "string three")

我将如何使用 for 循环来提取每个字符串,考虑到字符串有空格,所以我需要提取整个字符串,即“字符串三”,然后在该 fo 循环内,它将处理结果。

例如

#! /bin/bash

clear
SimName=("Welcome" "Testing Region")
echo
echo
echo
echo
#cd dreamgrid/Opensim/bin

# for loop goes here

# processing below
#screen -S "$SimName" -d -m mono OpenSim.exe -inidirectory="Regions/$SimName"  # Needs altering to process each string
#sleep 2
#screen -r "$SimName"   # Needs chaging to show each string in turn.

# echo $SimName[1]   # something test to it with, but needs changing to show each string in turn.

在 BASIC 中很简单:

DIM A$(2)
A$(1) = "string one"
A$(2) = "string two"
FOR A=1 to 2
C$=A$(A)
FOR DL=1 TO 2000
NEXT
PRINT C$
NEXT

答案1

语法是

for val in "${arr[@]}"; do 
  # something with "$val"
done

前任。

$ arr=("string one" "string two" "string three")
$ for val in "${arr[@]}"; do printf '%s\n' "$val"; done
string one
string two
string three

的双引号"${arr[@]}"使得它能够正确处理包含空格(或者更一般地说,来自当前的字符IFS)的元素。来自man bash

                                                                       If
   the word is double-quoted, ${name[*]} expands to a single word with the
   value of each array member separated by the first character of the  IFS
   special variable, and ${name[@]} expands each element of name to a sep‐
   arate word.

相关内容