[Top][All Lists]

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: which paradigms does bash support

From: Greg Wooledge
Subject: Re: which paradigms does bash support
Date: Mon, 26 Jan 2015 08:43:31 -0500
User-agent: Mutt/

On Sun, Jan 25, 2015 at 08:11:41PM -0800, address@hidden wrote:
> As a programming language which paradigms does bash support. Declarative, 
> procedural, imperative?

This belongs on address@hidden 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.


# 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 "address@hidden"; do
  ssh "$host" some command

# An if statement.

if grep -q "$keyword" "$inputfile"; then
  echo "Found $keyword in $inputfile"

# A case statement.

case "$inputfile" in
  *.gif | *.jpg | *.png) xv "$inputfile" ;;
  *.mp3 | *.ogg | *.wav) mplayer "$inputfile" ;;

reply via email to

[Prev in Thread] Current Thread [Next in Thread]