Changes

Jump to navigation Jump to search
1,447 bytes added ,  14:35, 15 July 2016
add arrays
<source lang="bash">
for i in `seq 1 10`; do echo "$i, "; done
</source>
 
== Arrays ==
In Bash v4 you can use multi-dimensional array but if you might want to use a different language. See http://wiki.bash-hackers.org/syntax/arrays for more.
 
Simple arrays work like the following:
<source lang="bash">
#!/bin/bash
 
# declare three arrays
# you can use the 'declare' built-in, but don't have to
# declare -a breakfast=('eggs' 'pancakes' 'cereal')
breakfast=('eggs' 'pancakes' 'cereal')
lunch=('sandwich' 'salad' 'smoothie')
dinner=('pasta' 'stir-fry' 'burritos')
 
# Now how do we loop through them?
# We could just output the values for breakfast
for i in "${breakfast[@]}"
# for BASH 3+ we have ! to access the numeric index
for i in "${!breakfast[@]}"
# Or, Build a sequence to loop through the other arrays by index
# while using a counter that is more friendly
# Arrays are indexed using integers and are zero-based
# the index number (starting at zero) gives that element
for (( i=1; i<${#breakfast}; i++ ))
do
echo "Here is the menu for day ${i}"
echo "breakfast: ${breakfast[$i-1]}"
echo "lunch: ${lunch[$i-1]}"
echo "dinner: ${dinner[$i-1]}"
done
 
 
declare -a fruits=('apples' 'oranges' 'banannas')
declare -a vegetables=('broccoli' 'onions' 'peppers' 'potatoes' 'carrots')
 
# the # character gives us the count of the array
echo "we have ${#fruits[@]} fruits available"
 
printf "%s\n" "${fruits[@]}"
echo "we have ${#vegetables[@]} vegetables available"
 
printf "%s\n" "${vegetables[@]}"
</source>
4,558

edits

Navigation menu