How do i use functions in bash shell scripts?



  • Functions help organise related task into a block of code. Functions can exist in a shell environment and in a shell script.

    Here's an example of a function within a shell script called functionscript.sh.

    #!/bin/bash
    show_status() {
    echo "Who is on the system"
    who
    echo "How long has the system been up"
    uptime
    }
    
    show_status
    

    When you run the script:

    $ ./functionscript.sh
    trainer :1           2017-09-01 08:04 (:1)
    How long has the system been up
     18:33:06 up 19:58,  1 user,  load average: 0.46, 0.67, 0.42
    

    Line number 1
    Is the name of the function followed by open/close parenthesis, followed by an open left curly bracket.

    Line numbers 3 - 6
    Is the block code, what you need the function to do.

    Line number 7
    Closes the function with a right curly bracket.

    Line number 9
    Is the name of the function, which executes the function.

    Notes:
    curly brackets are also known as curly braces
    Some users also define line number one as:

    function show_status {
    code
    }
    

    It is more common to use the format as per the example.


Log in to reply
 

© Lightnetics 2024