Difference between revisions of "CSC231 Bash Tutorial 8"

From dftwiki3
Jump to: navigation, search
(Created page with "--~~~~ ---- =Bash Functions= <br /> There are two ways of declaring functions in bash, illustrated in the code below: <br /> ::<source lang="bash"> #! /bin/bash # func1.sh # ...")
 
(Bash Functions)
Line 26: Line 26:
  
 
</source>
 
</source>
 +
<br />
 +
* Create the script above, make it executable, and run it, to see how it works.
 +
* Add a call to printSomething inside the printSomethingElse function, just to see if functions can actually call functions...  Does bash accept nested calls?
 +
<br />
 +
=Passing Arguments=
 +
<br />
 +
* Inside a function, $1 will refer to the first parameter passed to the function, $2 will refer to the second argument, etc.
 +
* Here is an example, with both style functions:
 +
<br />
 +
::<source lang="bash">
 +
#! /bin/bash
 +
# func1.sh
 +
# D. Thiebaut
 +
 +
printBar() {
 +
    echo "------------------------"
 +
}
 +
 +
function printName {
 +
    echo "Hello $1"
 +
}
 +
 +
function printAge {
 +
    echo "Your age: $1"
 +
}
 +
 +
 +
printBar
 +
printName "Kathleen McCartney"
 +
printAge  61
 +
printBar
 +
</source>
 +
<br />

Revision as of 13:23, 1 November 2017

--D. Thiebaut (talk) 13:13, 1 November 2017 (EDT)


Bash Functions


There are two ways of declaring functions in bash, illustrated in the code below:

#! /bin/bash
# func1.sh
# D. Thiebaut
# prints some messages

printSomething() {
    echo "Hello there!"
}

function printSomethingElse {
    echo "Hello again!"
}

printSomething
printSomething
printSomethingElse


  • Create the script above, make it executable, and run it, to see how it works.
  • Add a call to printSomething inside the printSomethingElse function, just to see if functions can actually call functions... Does bash accept nested calls?


Passing Arguments


  • Inside a function, $1 will refer to the first parameter passed to the function, $2 will refer to the second argument, etc.
  • Here is an example, with both style functions:


#! /bin/bash
# func1.sh
# D. Thiebaut

printBar() {
    echo "------------------------"
}

function printName {
    echo "Hello $1"
}

function printAge {
    echo "Your age: $1"
}


printBar
printName "Kathleen McCartney"
printAge  61
printBar