Open main menu

Changes

1,562 bytes added ,  10:41, 7 September 2017
no edit summary
<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>
* [http://penguinpetes.com/b2evo/index.php?title=how_the_one_liner_for_loop_in_bash_goes Penguin Pete]
* [[wp:Bash|Wikipedia page]]
* [https://ss64.com/bash/test.html Bash tests] <code>-f -d -x -w -Z </code> What do all the file test options mean?
[[Category:System Administration]]
4,558

edits