Last Updated: July 17, 2023
·
117.6K
· dpashkevich

Default parameter value in bash

If your bash function or a script takes parameters, there's a neat trick to give it a default value:

VAR=${1:-DEFAULTVALUE}    

Sets VAR with the value of first argument, and if the argument is not set, DEFAULTVALUE is used. Notice the colon and dash characters.

Here's a real world example of this feature found in @vinit's pro tip:

function server() {
    local port="${1:-8000}"
    python -m SimpleHTTPServer "$port"
}

This little function starts a simple HTTP server that serves from current directory. You can optionally specify the port to listen which defaults to 8000.