How do i define arguments in bash functions?
-
Let's see the following script run, the idea is to see what variable get defined within the function and what get's defined outside.
$ cat bash.variables cargo() { echo "++++++++++++++++++++++" echo "I'm inside a function, let me out: $0 $1 $2" var1="Flashy speakers" echo variable inside the function is: $var1 echo "++++++++++++++++++++++" } var1="I've got my cargo on my ship" echo "what's on my ship: $var1" echo $0: $1 $2 cargo functionarg1 functionarg2 echo "what's on my ship: $var1" echo $0: $1 $2
$ ./bash.variables cameras radios what's on my ship: I've got my cargo on my ship ./bash.variables: cameras radios ++++++++++++++++++++++ I'm inside a function, let me out: ./bash.variables functionarg1 functionarg2 variable inside the function is: Flashy speakers ++++++++++++++++++++++ what's on my ship: Flashy speakers ./bash.variables: cameras radios
The variable inside the function are global, and the var1 that was defined outside the function is replaced with the value of the "var1" in the function.
Note: There is a statement "local" that can be used to keep the variable local to a function.
© Lightnetics 2024