Skip to content

Instantly share code, notes, and snippets.

@stephenmm
Forked from caruccio/bash-named-param
Last active July 23, 2018 20:36
Show Gist options
  • Save stephenmm/9b2ac95ccc22a07dc9d2e61badcc59be to your computer and use it in GitHub Desktop.
Save stephenmm/9b2ac95ccc22a07dc9d2e61badcc59be to your computer and use it in GitHub Desktop.
Named parameters in bash
# Do you like python named parameters (kvargs) ?
# Well, you can have it in bash too!! (but unfortunatly this will not allow you to mix positional and named parameters)
function myfunc() { local $*; echo "# foo=$foo, bar=$bar"; }
myfunc bar=world foo=hello
# foo=hello, bar=world
#########
# And with default arguments:
function myfunc() {
local $*;
local foo; # No default
local bar; bar="${bar-bar_default}";
echo "# foo=$foo, bar=$bar";
}
myfunc
# foo=, bar=bar_default
myfunc foo=hello
# foo=hello, bar=bar_default
myfunc bar=world foo=hello
# foo=hello, bar=world
myfunc bar=world
# foo=, bar=world
#########
# Now lets add a check to make sure foo is provided:
function myfunc() {
requirerments="Must be called with ${FUNCNAME[0]} foo=something"
local $*;
local foo; [[ -z $foo ]] && echo "# Error: $requirerments: $( type ${FUNCNAME[0]} )" >&2 && return 1;
local bar="${bar-bar_default}";
echo "# foo=$foo, bar=$bar";
}
myfunc foo=hello
# foo=hello, bar=bar_default
myfunc bar=world foo=hello
# foo=hello, bar=world
myfunc bar=world
# Error myfunc requires foo: myfunc is a function
myfunc ()
{
requirerments="Must be called with ${FUNCNAME[0]} foo=something";
local $*;
local foo;
local bar;
bar="${bar-bar_default}";
[[ -z $foo ]] && echo "Error ${FUNCNAME[0]} requires foo: $( type ${FUNCNAME[0]} )";
echo "# foo=$foo, bar=$bar"
}
myfunc
# Error: Must be called with myfunc foo=something: myfunc is a function
myfunc ()
{
requirerments="Must be called with ${FUNCNAME[0]} foo=something";
local $*;
local foo;
local bar;
bar="${bar-bar_default}";
[[ -z $foo ]] && echo "Error: $requirerments: $( type ${FUNCNAME[0]} )";
echo "# foo=$foo, bar=$bar"
}
# foo=, bar=bar_default
myfunc foo=hello
# foo=hello, bar=bar_default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment