Skip to content

Instantly share code, notes, and snippets.

@YumaInaura
Last active August 30, 2018 23:48
Show Gist options
  • Save YumaInaura/dc13022e82401e6381b6ff6430a94b0f to your computer and use it in GitHub Desktop.
Save YumaInaura/dc13022e82401e6381b6ff6430a94b0f to your computer and use it in GitHub Desktop.
Bash — Define function by dynamic using variable

Bash — Define function by dynamic using variable

Example

Define function name variable

function_name="some_func"

Eval

eval "function $function_name() { echo ok this is dynamic function; }"

Or another style

eval function "$function_name"\(\) \{ echo ok this is dynamic function\; \}

Above examples both evaluated as below.

function some_func(){ echo ok this is dynamic function; }

Only $function_name is expanded as shell variable before eval evaluating.

Execute

$ some_func
ok this is dynamic function

Versions

  • bash-4.4
  • sh-3.2
  • GNU bash, version 3.2.57(1)-release (x86_64-apple-darwin17)

Links

#!/usr/bin/env bash -eu
function_name="some_func"
eval "function $function_name() { echo ok this is dynamic function; }"
some_func
# ok this is dynamic function
type some_func
# some_func is a function
# some_func ()
# {
# echo ok this is dynamic function
# }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment