Bash functions

No scripting language would be worth much without the ability to write functions or subroutines, blocks of reusable code.

Bash provides simple functions, using a Perlish model of not using predefined named parameters, just using $1, $2 etc:

function hello() {
    echo "Hello, $1"
hello Dave

Subsequent parameters are obviously $2, $3 etc.

Handling lots of parameters

You need to pass lots of parameters, maybe you don't know how many in advance? Use $* :

function hello() {
    for PERSON in $*; do
        echo "Hello, $PERSON";
hello Dave Bob Brian
# fine for globbing too:
hello /tmp/people/*
bash/functions.txt · Last modified: 2010/02/26 10:45 (external edit)
Recent changes RSS feed Donate Powered by PHP Valid XHTML 1.0 Valid CSS Driven by DokuWiki