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
.
Written by Dmitry Pashkevich
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Default
Authors
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#