iTranslated by AI
Various Bash Features
When writing shell scripts, you often hear things like, "That's a bash-exclusive feature" or "That's not in the POSIX shell." Most of the time, the response is "I thought it was part of the POSIX standard because everyone uses it." In this article, I will introduce various bash features, ranging from the useful ones to those that make you think, "Wait, if you're doing that, wouldn't Python be better?"
Using C-style loops in for statements
When it comes to for loops in shell scripts, for i in $(seq 10) is often used, but in bash, you can write it as follows:
for ((i=1;i<=10;i++)) ; do
echo "${i}"
done
It's not available in the POSIX shell, but it's convenient—especially for manual command entry—so I use it frequently.
Regular Expressions
You can use regular expressions by writing as follows:
VAR=foo
if [[ "${VAR}" =~ fo ]] ; then
echo matched
fi
I use this occasionally, but in most cases, I just manage with grep or sed. While bash's built-in regular expressions are faster than calling grep or sed and slightly easier to read, there are few situations where you need to worry about speed in shell scripts. If you are concerned about readability, it is better to use another language.
Arrays
You can use arrays as follows:
array=("foo" "bar" "baz")
for e in "${array[@]}" ; do
echo "${e}"
done
You can also access elements using indices like this:
for i in "${!array[@]}" ; do
echo "${array[i]}"
done
I have never used this for anything other than toy programs. I would rather use Python than use this.
Map
You can also use maps as follows:
declare -A map=(["foo"]="hoge" ["bar"]="huga" ["baz"]="piyo")
for k in "${!map[@]}" ; do
echo "${map[$k]}"
done
I have never used this for anything other than toy programs either.
Conclusion
There are many other things bash can do, so if you're interested, take a look at man bash.
Discussion