Loop through an array of strings in Bash?

2018-12-31 13:46发布

I want to write a script that loops through 15 strings (array possibly?) Is that possible?

Something like:

for databaseName in listOfNames
then
  # Do something
end

18条回答
谁念西风独自凉
2楼-- · 2018-12-31 14:38

Try this. It is working and tested.

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

# For accessing with the echo command: echo ${array[0]}, ${array[1]}
查看更多
与风俱净
3楼-- · 2018-12-31 14:39

Possible first line of every Bash script/session:

say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }

Use e.g.:

$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e

May consider: echo interprets -e as option here

查看更多
美炸的是我
4楼-- · 2018-12-31 14:40

This is similar to user2533809's answer, but each file will be executed as a separate command.

#!/bin/bash
names="RA
RB
R C
RD"

while read -r line; do
    echo line: "$line"
done <<< "$names"
查看更多
荒废的爱情
5楼-- · 2018-12-31 14:41

The declare array doesn't work for Korn shell. Use the below example for the Korn shell:

promote_sla_chk_lst="cdi xlob"

set -A promote_arry $promote_sla_chk_lst

for i in ${promote_arry[*]};
    do
            echo $i
    done
查看更多
牵手、夕阳
6楼-- · 2018-12-31 14:43

Surprised that nobody's posted this yet -- if you need the indices of the elements while you're looping through the array, you can do this:

arr=(foo bar baz)

for i in ${!arr[@]}
do
    echo $i "${arr[i]}"
done

Output:

0 foo
1 bar
2 baz

I find this a lot more elegant than the "traditional" for-loop style (for (( i=0; i<${#arr[@]}; i++ ))).

(${!arr[@]} and $i don't need to be quoted because they're just numbers; some would suggest quoting them anyway, but that's just personal preference.)

查看更多
无色无味的生活
7楼-- · 2018-12-31 14:45

I loop through an array of my projects for a git pull update:

#!/bin/sh
projects="
web
ios
android
"
for project in $projects do
    cd  $HOME/develop/$project && git pull
end
查看更多
登录 后发表回答