我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
我想写一个循环15个字符串的脚本(可能是数组?)这可能吗?
类似于:
for databaseName in listOfNames
then
# Do something
end
当前回答
每个Bash脚本/会话的可能第一行:
say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }
使用例如:
$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e
可以考虑:echo在此处将-e解释为选项
其他回答
当然,这是可能的。
for databaseName in a b c d e f; do
# do something like: echo $databaseName
done
有关详细信息,请参阅、while和until的Bash循环。
单线循环,
declare -a listOfNames=('db_a' 'db_b' 'db_c')
for databaseName in ${listOfNames[@]}; do echo $databaseName; done;
你会得到这样的输出,
db_a
db_b
db_c
我循环浏览一系列项目以进行git pull更新:
#!/bin/sh
projects="
web
ios
android
"
for project in $projects do
cd $HOME/develop/$project && git pull
end
listOfNames="db_one db_two db_three"
for databaseName in $listOfNames
do
echo $databaseName
done
或者只是
for databaseName in db_one db_two db_three
do
echo $databaseName
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