Tutorial by Examples

In helloWorld.sh #!/bin/bash # Define a function greet greet () { echo "Hello World!" } # Call the function greet greet In running the script, we see our message $ bash helloWorld.sh Hello World! Note that sourcing a file with functions makes them available in your ...
In helloJohn.sh: #!/bin/bash greet() { local name="$1" echo "Hello, $name" } greet "John Doe" # running above script $ bash helloJohn.sh Hello, John Doe If you don't modify the argument in any way, there is no need to copy it to a local variabl...
The return statement in Bash doesn't return a value like C-functions, instead it exits the function with a return status. You can think of it as the exit status of that function. If you want to return a value from the function then send the value to stdout like this: fun() { local var="S...
The getopts builtin can be used inside functions to write functions that accommodate flags and optional parameters. This presents no special difficulty but one has to handle appropriately the values touched by getopts. As an example, we define a failwith function that writes a message on stderr an...
Consider this example function to check if a host is up: is_alive() { ping -c1 "$1" &> /dev/null } This function sends a single ping to the host specified by the first function parameter. The output and error output of ping are both redirected to /dev/null, so the functi...
getfunc() { declare -f "$@" } function func(){ echo "I am a sample function" } funcd="$(getfunc func)" getfunc func # or echo "$funcd" Output: func () { echo "I am a sample function" }
foo() { while [[ "$#" -gt 0 ]] do case $1 in -f|--follow) local FOLLOW="following" ;; -t|--tail) local TAIL="tail=$2" ;; esac shift done echo "FOLLOW: $FOLLOW" echo "TAIL: $...

Page 1 of 1