Hello World (bash)

From LiteratePrograms
Jump to: navigation, search
Other implementations: Alice ML | Amiga E | Assembly Intel x86 Linux | Assembly Intel x86 NetBSD | AWK | bash | BASIC | Batch files | C | C, Cairo | C, Xlib | Candle | C++ | C# | Dylan | E | Forth | FORTRAN | Fortress | Go | Groovy | IBM PC bootstrap | Inform 7 | JavaScript | LaTeX | Logo | Lua | MATLAB | OCaml/F Sharp | occam | Oz | Perl | PHP | PIR | PLI | Prolog | Python | Rexx | Ruby | Scheme | sh | SQL | Standard ML | Tcl | Tcl Tk | Visual Basic

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
hijacker
hijacker
hijacker
hijacker