Greg Wooledge
2015-01-26 13:43:31 UTC
As a programming language which paradigms does bash support. Declarative, procedural, imperative?
This belongs on help-***@gnu.org so I'm Cc'ing that address.Shell scripts are procedural.
The control structures are while loops, for loops, procedure calls
(which are called "functions" but aren't really), if statements, and
case statements. There are no gotos, and nothing analogous.
Examples:
# This is a "function". It can only return a value that indicates whether
# it succeeded (0), or failed (1-255). There is no way to pass variables
# "by reference". The arguments are just strings. Functions may be
# recursive, and local variables are supported. Variable scoping is
# dynamic.
# The biggest issue with bash's functions is how to get information out
# of them. Since there is no pass-by-reference, and the return value
# is just a success indicator, you're stuck with writing the results to
# a global variable (or higher-scope variable), writing the results to
# a file on disk, or writing the results to stdout and making the caller
# "capture" it with a command substitution. The last choice is very
# common, but it forces bash to fork() and run the function in a subshell,
# so performance is abysmal, and the subshell prevents other side effects
# from occurring (which may be desirable or not).
process() {
local var1 var2
some code that uses argument "$1"
return 0
}
# A common while loop.
while read line; do
process "$line"
done < "$inputfile"
# An array declaration, and a for loop.
hosts=(ares athena hermes zeus)
for host in "${hosts[@]}"; do
ssh "$host" some command
done
# An if statement.
if grep -q "$keyword" "$inputfile"; then
echo "Found $keyword in $inputfile"
fi
# A case statement.
case "$inputfile" in
*.gif | *.jpg | *.png) xv "$inputfile" ;;
*.mp3 | *.ogg | *.wav) mplayer "$inputfile" ;;
esac