在Bash中循環遍歷字符串數組?

我想編寫一個經過15個字符串循環的腳本(多是數組嗎?)那可能嗎? shell

就像是: 數組

for databaseName in listOfNames
then
  # Do something
end

#1樓

該聲明數組不適用於Korn shell。 將如下示例用於Korn shell: bash

promote_sla_chk_lst="cdi xlob"

set -A promote_arry $promote_sla_chk_lst

for i in ${promote_arry[*]};
    do
            echo $i
    done

#2樓

嘗試這個。 它正在工做並通過測試。 ide

for k in "${array[@]}"
do
    echo $k
done

# For accessing with the echo command: echo ${array[0]}, ${array[1]}

#3樓

本着與4ndrew的回答相同的精神: oop

listOfNames="RA
RB
R C
RD"

# To allow for other whitespace in the string:
# 1. add double quotes around the list variable, or
# 2. see the IFS note (under 'Side Notes')

for databaseName in "$listOfNames"   #  <-- Note: Added "" quotes.
do
  echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
done

# Outputs
# RA
# RB
# R C
# RD

B.名稱中不能有空格: 測試

listOfNames="RA
RB
R C
RD"

for databaseName in $listOfNames  # Note: No quotes
do
  echo "$databaseName"  # (i.e. do action / processing of $databaseName here...)
done

# Outputs
# RA
# RB
# R
# C
# RD

筆記 spa

  1. 在第二個示例中,使用listOfNames="RA RB RC RD"具備相同的輸出。

引入數據的其餘方式包括: code

從stdin讀取 three

# line delimited (each databaseName is stored on a line)
while read databaseName
do
  echo "$databaseName"  # i.e. do action / processing of $databaseName here...
done # <<< or_another_input_method_here
  1. 能夠在腳本中指定bash IFS 「行分隔符」 [ 1 ]分隔符,以容許其餘空格(即IFS='\\n'或MacOS IFS='\\r'
  2. 我也喜歡接受的答案:)-我將這些摘要做爲其餘有用的方式也能夠回答問題。
  3. 腳本文件頂部包含#!/bin/bash表示執行環境。
  4. 我花了幾個月的時間弄清楚如何簡單地編寫此代碼:)

其餘來源( 讀取循環時字符串


#4樓

您能夠使用${arrayName[@]}的語法

#!/bin/bash
# declare an array called files, that contains 3 values
files=( "/etc/passwd" "/etc/group" "/etc/hosts" )
for i in "${files[@]}"
do
    echo "$i"
done

#5樓

這些答案都沒有包含計數器...

#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

輸出:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three
相關文章
相關標籤/搜索