我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
当前回答
当然,这是可能的。
for databaseName in a b c d e f; do
# do something like: echo $databaseName
done
有关详细信息,请参阅、while和until的Bash循环。
其他回答
脚本或函数的隐式数组:
除了anubhava的正确答案:如果循环的基本语法是:
for var in "${arr[@]}" ;do ...$var... ;done
bash中有一个特殊情况:
当运行脚本或函数时,在命令行传递的参数将被分配给$@数组变量,您可以通过$1、$2、$3等进行访问。
可以通过以下方式填充(用于测试)
set -- arg1 arg2 arg3 ...
这个数组上的循环可以简单地写:
for item ;do
echo "This is item: $item."
done
请注意,中的保留工作不存在,也没有数组名称!
示例:
set -- arg1 arg2 arg3 ...
for item ;do
echo "This is item: $item."
done
This is item: arg1.
This is item: arg2.
This is item: arg3.
This is item: ....
注意,这与
for item in "$@";do
echo "This is item: $item."
done
然后进入脚本:
#!/bin/bash
for item ;do
printf "Doing something with '%s'.\n" "$item"
done
将其保存在脚本myscript.sh、chmod+x myscript.shh中,然后
./myscript.sh arg1 arg2 arg3 ...
Doing something with 'arg1'.
Doing something with 'arg2'.
Doing something with 'arg3'.
Doing something with '...'.
在函数中相同:
myfunc() { for item;do cat <<<"Working about '$item'."; done ; }
Then
myfunc item1 tiem2 time3
Working about 'item1'.
Working about 'tiem2'.
Working about 'time3'.
您可以使用${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
这与user2533809的答案类似,但每个文件都将作为单独的命令执行。
#!/bin/bash
names="RA
RB
R C
RD"
while read -r line; do
echo line: "$line"
done <<< "$names"
试试这个。它正在运行和测试。
for k in "${array[@]}"
do
echo $k
done
# For accessing with the echo command: echo ${array[0]}, ${array[1]}
循环遍历数组的方式取决于换行符的存在。使用分隔数组元素的换行符,数组可以称为“$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