- #!/bin/bash
- # Basic function
- print_something () {
- echo Hello I am a function
- }
- print_something
- print_something
- ./function_example.sh
- Hello I am a function
- Hello I am a function
Passing Arguments
It is often the case that we would like the function to process some data for us. We may send data to the function in a similar way to passing command line arguments to a script. We supply the arguments directly after the function name. Within the function they are accessible as $1, $2, etc.
- #!/bin/bash
- # Passing arguments to a function
- print_something () {
- echo Hello $1
- }
- print_something Mars
- print_something Jupiter
- ./arguments_example.sh
- Hello Mars
- Hello Jupiter
Return Values
Most other programming languages have the concept of a return value for functions, a means for the function to send data back to the original calling location. Bash functions don't allow us to do this. They do however allow us to set a return status. Similar to how a program or command exits with an exit status which indicates whether it succeeded or not. We use the keyword return to indicate a return statu
- #!/bin/bash
- # Setting a return status for a function
- print_something () {
- echo Hello $1
- return 5
- }
- print_something Mars
- print_something Jupiter
- echo The previous function has a return value of $?
Line 11 - Remember that the variable $? contains the return status of the previously run command or function.
- ./return_status_example.sh
- Hello Mars
- Hello Jupiter
- The previous function has a return value of 5
Example2
- #!/bin/bash
- # Setting a return value to a function
- lines_in_file () {
- cat $1 | wc -l
- }
- num_lines=$( lines_in_file $1 )
- echo The file $1 has $num_lines lines in it.
Let's break it down:
- Line 5 - This command will print the number of lines in the file referred to by $1.
- Line 8 - We use command substitution to take what would normally be printed to the screen and assign it to the variable num_lines
- cat myfile.txt
- Tomato
- Lettuce
- Capsicum
- ./return_hack.sh myfile.txt
- The file myfile.txt has 3 lines in it.
Example3
- #!/bin/bash
- # Experimenting with variable scope
- var_change () {
- local var1='local 1'
- echo Inside function: var1 is $var1 : var2 is $var2
- var1='changed again'
- var2='2 changed again'
- }
- var1='global 1'
- var2='global 2'
- echo Before function call: var1 is $var1 : var2 is $var2
- var_change
- echo After function call: var1 is $var1 : var2 is $var2
- ./local_variables.sh
- Before function call: var1 is global 1 : var2 is global 2
- Inside function: var1 is local 1 : var2 is global 2
- After function call: var1 is global 1 : var2 is 2 changed again
No comments:
Post a Comment