cst8102-16f_08 - Understanding Functions Functions are...

This preview shows page 1 - 9 out of 30 pages.

Understanding Functions Functions are self-contained blocks of code Functions can accept values and return a result Function code can be reused Functions reduce redundancy Functions provide for modular code
Understanding Function Parts General format of a function in the shell: function function-name () { statements } Function name is required The keyword “ function ” or the parentheses are required but can use both The left and right braces are required The statements are any valid shell commands You use a function by using its name known as a function call
Understanding Functions function displayhello () { echo hello } displayhello displayhello () { echo hello } displayhello
Implementing Functions Functions are usually placed at the beginning of the script or prior to the function call Once the function is called, the shell executes the statements within the function. After the function has completed, the shell returns control to subsequent statements A function called prior to its definition will generate a command not found ” error
A Function Calling Another Function function test1 () { echo “this is test1” test2 echo “end of test1” } function test2 () { echo “this is test2” } test1 echo “All done”
Implementing Functions Avoiding errors: Use the keyword “function” or () after the function name Do not add parentheses after the name when calling the function Functions can be created using an editor or functions can be created directly in the shell
Passing Values to Functions You can pass values to functions making them more flexible Once the value is passed, the function can perform calculations or comparisons Values are positional Example: function DisplayIt () { echo $1 $2 } DisplayIt $2 $1 $ display_it 3 6
Passing Values to Functions compare () { if [ $1

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture