我陷入了困境,我正在嘗試編寫一個 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.