quick and dirty function doc
This commit is contained in:
		
							parent
							
								
									4a7606507d
								
							
						
					
					
						commit
						77ea7d4c79
					
				|  | @ -1197,16 +1197,110 @@ done | |||
| 
 | ||||
| ## defining a function | ||||
| 
 | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| function say_hello() { | ||||
| 	echo "hello world" | ||||
| } | ||||
| 
 | ||||
| say_hello | ||||
| say_hello | ||||
| say_hello | ||||
| ``` | ||||
| 
 | ||||
| ## function arguments | ||||
| 
 | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| function say_hello() { | ||||
| 	echo "hello $1" | ||||
| } | ||||
| 
 | ||||
| say_hello | ||||
| say_hello "Alice" | ||||
| say_hello "Steve" "Camille" | ||||
| ``` | ||||
| 
 | ||||
| ## global vs local variable | ||||
| 
 | ||||
| ### global example | ||||
| 
 | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| default="my friend" | ||||
| 
 | ||||
| function say_hello() { | ||||
| 	if ! [[ -z $1 ]]; then | ||||
| 		default=$1 | ||||
| 	fi | ||||
| 	echo "hello $default" | ||||
| } | ||||
| 
 | ||||
| say_hello | ||||
| say_hello "Alice" | ||||
| say_hello  | ||||
| ``` | ||||
| ### local example | ||||
| 
 | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| default="my friend" | ||||
| 
 | ||||
| function say_hello() { | ||||
| 	if ! [[ -z $1 ]]; then | ||||
| 		local name=$1 | ||||
| 	else | ||||
| 		local name=$default | ||||
| 	fi | ||||
| 	echo "hello $name" | ||||
| } | ||||
| 
 | ||||
| say_hello | ||||
| say_hello "Alice" | ||||
| say_hello | ||||
| ``` | ||||
| 
 | ||||
| ## return values | ||||
| 
 | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| function add_two_numbers() { | ||||
| 	if [[ -z $1 ]] && [[ -z $2 ]]; then | ||||
| 		echo "I need two arguments!" | ||||
| 		return 1 | ||||
| 	elif ! [[ "$1" =~ ^[0-9]+$ ]] || ! [[ "$2" =~ ^[0-9]+$ ]]; then | ||||
| 		echo "arguments need to be numbers!" | ||||
| 		return 2 | ||||
| 	fi | ||||
| 	echo "$1 + $2 = $(( $1 + $2 ))" | ||||
| 	return 0 | ||||
| } | ||||
| 
 | ||||
| add_two_numbers | ||||
| echo $? | ||||
| add_two_numbers "Alice" "Bob" | ||||
| echo $? | ||||
| add_two_numbers 3 4 | ||||
| echo $? | ||||
| ``` | ||||
| 
 | ||||
| ## the `command` builtin | ||||
| 
 | ||||
| [Ryan's tutorials](https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php) | ||||
| ```bash | ||||
| #!/bin/bash | ||||
| 
 | ||||
| function ls () { | ||||
| 	echo "I'm a function..." | ||||
| } | ||||
| 
 | ||||
| ls | ||||
| command ls /etc/ssh/ | ||||
| ``` | ||||
| 
 | ||||
| # Coding challenge - pipe or argument plus action! | ||||
| 
 | ||||
|  |  | |||
		Loading…
	
		Reference in New Issue