Bash Functions with arguments


Example

In helloJohn.sh:

#!/bin/bash

greet() {
  local name="$1"
  echo "Hello, $name"
}

greet "John Doe"
# running above script
$ bash helloJohn.sh
Hello, John Doe
  1. If you don't modify the argument in any way, there is no need to copy it to a local variable - simply echo "Hello, $1".

  2. You can use $1, $2, $3 and so on to access the arguments inside the function.

    Note: for arguments more than 9 $10 won't work (bash will read it as $10), you need to do ${10}, ${11} and so on.

  3. $@ refers to all arguments of a function:

    #!/bin/bash
    foo() {
      echo "$@"
    }
    
    foo 1 2 3 # output => 1 2 3
    

    Note: You should practically always use double quotes around "$@", like here.

    Omitting the quotes will cause the shell to expand wildcards (even when the user specifically quoted them in order to avoid that) and generally introduce unwelcome behavior and potentially even security problems.

    foo "string with spaces;" '$HOME' "*"
    # output => string with spaces; $HOME *
    
  4. for default arguments use ${1:-default_val}. Eg:

    #!/bin/bash
    foo() {
      local val=${1:-25}
      echo "$val"
    }
    
    foo     # output => 25
    foo 30  # output => 30
    
  5. to require an argument use ${var:?error message}

    foo() {
      local val=${1:?Must provide an argument}
      echo "$val"
    }