我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?

类似于:

for databaseName in listOfNames
then
  # Do something
end

当前回答

我真正需要的是这样的东西:

for i in $(the_array); do something; done

例如:

for i in $(ps -aux | grep vlc  | awk '{ print $2 }'); do kill -9 $i; done

(将终止所有以vlc命名的进程)

其他回答

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

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

笔记

在第二个示例中,使用listOfNames=“RA RB R C RD”具有相同的输出。

其他引入数据的方法包括:

stdin(如下所列),变量,数组(接受的答案),文件。。。

从stdin读取

# 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

可以在脚本中指定bash IFS“字段分隔符到行”[1]分隔符,以允许其他空格(即IFS='\n',或MacOS IFS='\r')我也喜欢接受的答案:)--我将这些片段作为其他有用的方式来回答这个问题。包括#/脚本文件顶部的bin/bash指示执行环境。我花了几个月的时间才弄清楚如何简单地编写代码:)

其他来源(读取循环时)

简单方法:

arr=("sharlock"  "bomkesh"  "feluda" )  ##declare array

len=${#arr[*]}  # it returns the array length

#iterate with while loop
i=0
while [ $i -lt $len ]
do
    echo ${arr[$i]}
    i=$((i+1))
done


#iterate with for loop
for i in $arr
do
  echo $i
done

#iterate with splice
 echo ${arr[@]:0:3}

试试这个。它正在运行和测试。

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

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

如果您使用的是Korn shell,则有“set-A databaseName”,否则有“declare-A databaseName”

要在所有外壳上编写脚本,

 set -A databaseName=("db1" "db2" ....) ||
        declare -a databaseName=("db1" "db2" ....)
# now loop 
for dbname in "${arr[@]}"
do
   echo "$dbname"  # or whatever

done

它应该在所有外壳上工作。

循环遍历数组的方式取决于换行符的存在。使用分隔数组元素的换行符,数组可以称为“$array”,否则应称为“${array[@]}”。以下脚本将明确说明:

#!/bin/bash

mkdir temp
mkdir temp/aaa
mkdir temp/bbb
mkdir temp/ccc
array=$(ls temp)
array1=(aaa bbb ccc)
array2=$(echo -e "aaa\nbbb\nccc")

echo '$array'
echo "$array"
echo
for dirname in "$array"; do
    echo "$dirname"
done
echo
for dirname in "${array[@]}"; do
    echo "$dirname"
done
echo
echo '$array1'
echo "$array1"
echo
for dirname in "$array1"; do
    echo "$dirname"
done
echo
for dirname in "${array1[@]}"; do
    echo "$dirname"
done
echo
echo '$array2'
echo "$array2"
echo
for dirname in "$array2"; do
    echo "$dirname"
done
echo
for dirname in "${array2[@]}"; do
    echo "$dirname"
done
rmdir temp/aaa
rmdir temp/bbb
rmdir temp/ccc
rmdir temp