Bash shell scripts support functions, which allow you to group related commands and statements, and perform operations on the data passed to the function.
Here are some examples of functions in Bash shell scripts:
#!/usr/bin/env bash # Define the function hello() { echo "Hello, world!" } # Call the function hello
This function, called hello
, simply prints the message "Hello, world!" to standard output. The function is defined using the function_name() { ... }
syntax, and is called using the function name followed by any necessary arguments.
#!/usr/bin/env bash # Define the function greet() { echo "Hello, $1!" } # Call the function with an argument greet "John"
This function, called greet
, takes a string argument and prints a message using the argument. The function is defined using the function_name() { ... }
syntax, and is called using the function name followed by the desired argument (in this case, "John"
). The argument is accessed inside the function using the $1
variable, which represents the first argument passed to the function.
#!/usr/bin/env bash # Define the function sum() { result=$(( $1 + $2 )) echo "$1 + $2 = $result"