s8n9qa
Last Updated: February 25, 2016
·
510
· dpashkevich
D42a7264714dee5006b9c99d2567a320

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.

Say Thanks
Respond
Filed Under