我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
当前回答
如果您使用的是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
它应该在所有外壳上工作。
其他回答
这与user2533809的答案类似,但每个文件都将作为单独的命令执行。
#!/bin/bash
names="RA
RB
R C
RD"
while read -r line; do
echo line: "$line"
done <<< "$names"
当然,这是可能的。
for databaseName in a b c d e f; do
# do something like: echo $databaseName
done
有关详细信息,请参阅、while和until的Bash循环。
我在GitHub更新中使用了这种方法,我发现它很简单。
## declare an array variable
arr_variable=("kofi" "kwame" "Ama")
## now loop through the above array
for i in "${arr_variable[@]}"
do
echo "$i"
done
您可以使用带有三个表达式(C样式)的计数器遍历bash数组值,以读取循环语法的所有值和索引:
declare -a kofi=("kofi" "kwame" "Ama")
# get the length of the array
length=${#kofi[@]}
for (( j=0; j<${length}; j++ ));
do
print (f "Current index %d with value %s\n" $j "${kofi[$j]}")
done
每个Bash脚本/会话的可能第一行:
say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
使用例如:
$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e
可以考虑:echo在此处将-e解释为选项
您可以这样使用:
## declare an array variable
declare -a arr=("element1" "element2" "element3")
## now loop through the above array
for i in "${arr[@]}"
do
echo "$i"
# or do whatever with individual element of the array
done
# You can access them using echo "${arr[0]}", "${arr[1]}" also
也适用于多行数组声明
declare -a arr=("element1"
"element2" "element3"
"element4"
)