Java Programming Tutorials

Java programming tutorials with many code examples!

Bash array

Problem:

How to use Bash arrays? Bash is very flexible and allows to do funny things with arrays. Check out these cool Bash array examples.

Solution:

Declare an array with some items and print it:

declare -a langs=(Java Clojure Scala Python)
echo ${langs[@]}

Read items from standard input into an array:

while read lang; do
    langs=("${langs[@]}" $lang)
done
echo ${langs[@]}

Print length of an array:

echo ${#langs[@]} #prints: 4

Select part of (slice) of an array:

echo ${langs[@]:2:4}   #prints: Scala Python

Concatenate an array with itself:

ccc=(${langs[@]} ${langs[@]} ${langs[@]})
echo ${ccc[@]}

Replace starting uppercase characters in langs of an array:

while read lang; do
    langs=("${langs[@]}" $(echo $lang | sed 's/^[A-Z]/./'))
done
echo ${langs[@]} #prints: .ava .lojure .cala .ython

Filter an array with a pattern:

echo ${langs[@]/*[aA]*/} #prints: Clojure Python
Share with the World!