3

Always wondered this, but never fully investigated - is there any way to get named parameters in bash?

For example, I have this:

function ql_maybe_fail {
  if [[ "$1" == "true" ]]; then
      echo "quicklock: exiting with 1 since fail flag was set for your 'ql_release_lock' command. "
      exit 1;
  fi
}

is it somehow possible to convert it to something like this:

function ql_maybe_fail (isFail) {
  if [[ "$isFail" == "true" ]]; then
      echo "quicklock: exiting with 1 since fail flag was set for your 'ql_release_lock' command. "
      exit 1;
  fi
}
5
  • Or unix.stackexchange.com/questions/122632/…
    – muru
    Commented Mar 2, 2018 at 3:23
  • 1
    damn those answers are all so unclear...after reading, I guess the answer is a big fat no, lol Commented Mar 2, 2018 at 3:30
  • The best I've found is this answer over on StackOverflow - stackoverflow.com/a/7948533 Commented Mar 2, 2018 at 8:39
  • What's the problem that you are trying to solve that requires this to work?
    – Kusalananda
    Commented Mar 2, 2018 at 10:29
  • it's just for convenience - most programming languages have named arguments, etc, for a reason Commented Mar 3, 2018 at 20:57

2 Answers 2

6

Functions in Bash currently do not support user-named arguments.

0
4

This workaround might help, but it is not well testet:

fun () {
    v1=$1
    v2=$2
    for v in "$v1" "$v2"
    do
       case "$v" in
           name=*) name=${v/*=/};;
           age=*)  age=${v/*=/};;
           *)    echo "unexpected $v, please use name and age" ;;
       esac
    done

    echo "name=$name age=$age"
}

output:

fun "name=John" "age=22"
name=John age=22
fun "age=22" "name=John"
name=John age=22
3
  • yeah, it's just not the same lol Commented Mar 2, 2018 at 10:03
  • 3
    Well, for your sample (function ql_maybe_fail (isFail) {) just write function ql_maybe_fail () { isFail=$1 - where is the problem? Commented Mar 2, 2018 at 10:06
  • no problem just an extra line of code I guess Commented Mar 3, 2018 at 20:57

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.