Hello World (bash)

From LiteratePrograms

Jump to: navigation, search
Other implementations: Ada | ALGOL 68 | Alice ML | Amiga E | Applescript | AspectJ | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | Clojure | C++ | C# | Delphi | Dylan | E | Eiffel | Erlang | Forth | FORTRAN | Fortress | Go | Groovy | Haskell | Hume | IBM PC bootstrap | Inform 7 | Java | Java, Swing | JavaScript | LaTeX | Lisp | Logo | Lua | Maple | MATLAB | Mercury | OCaml/F Sharp | occam | Oz | Pascal | Perl | PHP | Pic | PIR | PLI | PostScript | Prolog | Python | Rexx | Ruby | Scala | Scheme | Seed7 | sh | Smalltalk | SQL | Standard ML | SVG | Tcl | Tcl Tk | Visual Basic | Visual Basic .NET | XSL

Hello world in the GNU Bourne-again Shell (bash):

The first line tells the operating system how to execute this script. When using bash, one problem which may be faced is that unlike with sh, there's no standard where bash is installed (it's /bin/bash on Linux systems, but may be /usr/bin/bash or even /usr/local/bin/bash on other Unix systems). This is a problem for portable scripts because the absolute path of the executable to run has to be encoded in the first line. Therefore the following script uses a common trick: There's a standard utility env found in the standard place /usr/bin/env. This utility is meant to allow calling programs with a modified environment, but the interesting part here is that to find the program to execute, it uses the normal search path, so the bash executable is found as long as it is in the path.

<<hello_world.sh>>=
#! /usr/bin/env bash

The second line is the actual script. "echo" is a built-in shell command, that writes all arguments to standard output.

<<hello_world.sh>>=
echo "Hello World!"

This is essentially the same program as Hello World (sh), but invokes a different shell. For a simple program like this, it makes little difference which shell is actually used. However, bash offers a number of features not found in the standard Bourne-shell which are useful for developing more complex scripts.

Download code
Views
Personal tools