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:20

You can use the syntax of ${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
查看更多
梦寄多情
3楼-- · 2018-12-31 14:21
listOfNames="db_one db_two db_three"
for databaseName in $listOfNames
do
  echo $databaseName
done

or just

for databaseName in db_one db_two db_three
do
  echo $databaseName
done
查看更多
不再属于我。
4楼-- · 2018-12-31 14:26

In the same spirit as 4ndrew's answer:

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. No whitespace in the names:

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

Notes

  1. In the second example, using listOfNames="RA RB R C RD" has the same output.

Other ways to bring in data include:

Read from 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
  1. the bash IFS "field separator to line" [1] delimiter can be specified in the script to allow other whitespace (i.e. IFS='\n', or for MacOS IFS='\r')
  2. I like the accepted answer also :) -- I've include these snippets as other helpful ways that also answer the question.
  3. Including #!/bin/bash at the top of the script file indicates the execution environment.
  4. It took me months to figure out how to code this simply :)

Other Sources (while read loop)

查看更多
一个人的天荒地老
5楼-- · 2018-12-31 14:28

None of those answers include a counter...

#!/bin/bash
## declare an array variable
declare -a array=("one" "two" "three")

# get length of an array
arraylength=${#array[@]}

# use for loop to read all values and indexes
for (( i=1; i<${arraylength}+1; i++ ));
do
  echo $i " / " ${arraylength} " : " ${array[$i-1]}
done

Output:

1  /  3  :  one
2  /  3  :  two
3  /  3  :  three
查看更多
忆尘夕之涩
6楼-- · 2018-12-31 14:28

Simple way :

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}
查看更多
高级女魔头
7楼-- · 2018-12-31 14:30

Yes

for Item in Item1 Item2 Item3 Item4 ;
  do
    echo $Item
  done

Output :

Item1
Item2
Item3
Item4

Over multiple lines

for Item in Item1 \
            Item2 \
            Item3 \
            Item4
  do
    echo $Item
  done

Output :

Item1
Item2
Item3
Item4


Simple list variable

List=( Item1 Item2 Item3 )

or

List=(
      Item1 
      Item2 
      Item3
     )

Display the list variable :

echo ${List[*]}

Out put :

Item1 Item2 Item3

Loop through the list:

for Item in ${List[*]} 
  do
    echo $Item 
  done

Out put :

Item1
Item2
Item3

Create a function to go through a list:

Loop(){
  for item in ${*} ; 
    do 
      echo ${item} 
    done
}
Loop ${List[*]}

To preserve spaces ; single or double quote list entries and double quote list expansions :

List=(' Item 1 '
      ' Item 2' 
      ' Item 3'
     )
for item in "${List[@]}"; 
  do 
    echo "$item"
  done 

Output :

 Item 1
 Item 2
 Item 3

Using the declare keyword (command) to create the list , which is technically called an array :

declare -a List=(
                 "element 1" 
                 "element 2" 
                 "element 3"
                )
for entry in "${List[@]}"
   do
     echo "$entry"
   done

Out put :

element 1
element 2
element 3

Creating an associative array . A dictionary :

declare -A continent

continent[Vietnam]=Asia
continent[France]=Europe
continent[Argentina]=America

for item in "${!continent[@]}"; 
  do
    printf "$item is in ${continent[$item]} \n"
  done

Output :

 Argentina is in America
 Vietnam is in Asia
 France is in Europe

CVS variables or files in to a list .
Changing the internal field separator from a space , to what ever you want .
In the example below it is changed to a comma

List="Item 1,Item 2,Item 3"
Backup_of_internal_field_separator=$IFS
IFS=,
for item in $List; 
  do
    echo $item
  done
IFS=$Backup_of_internal_field_separator

Output :

Item 1
Item 2
Item 3

If need to number them :

` 

this is called a back tick . Put the command inside back ticks .

`commend` 

It is next to the number one on your keyboard and or above the tab key . On a standard american english language keyboard .

List=()
Start_count=0
Step_count=0.1
Stop_count=1
for Item in `seq $Start_count $Step_count $Stop_count`
    do 
       List+=(Item_$Item)
    done
for Item in ${List[*]}
    do 
        echo $Item
    done

Out put is :

Item_0.0
Item_0.1
Item_0.2
Item_0.3
Item_0.4
Item_0.5
Item_0.6
Item_0.7
Item_0.8
Item_0.9
Item_1.0

Becoming more familiar with bashes behavior :

Create a list in a file

cat <<EOF> List_entries.txt
Item1
Item 2 
'Item 3'
"Item 4"
Item 7 : *
"Item 6 : * "
"Item 6 : *"
Item 8 : $PWD
'Item 8 : $PWD'
"Item 9 : $PWD"
EOF

Read the list file in to a list and display

List=$(cat List_entries.txt)
echo $List
echo '$List'
echo "$List"
echo ${List[*]}
echo '${List[*]}'
echo "${List[*]}"
echo ${List[@]}
echo '${List[@]}'
echo "${List[@]}"

BASH commandline reference manual : Special meaning of certain characters or words to the shell.

查看更多
登录 后发表回答