0

I have the following loop to read and set variables passed to a bash script

while [ $# -gt 0 ]; do

        if [[ $1 == *"--"* ]]; then
                param="${1/--/}"
                declare $param="$2"
                # echo $1 $2 // Optional to see the parameter:value result
        fi

        shift
done

For example one can call it via:

sh test.sh --name myname --family myfamily

How can I change it to call it as:

sh test.sh --name=myname --family=myfamily
2
  • Why? just use getopts or getopt Commented Jul 1, 2021 at 9:35
  • @Inian you mean getopts support = between option-value? However, I found above code or the modifcation in accepted answer an easy solution. Commented Jul 1, 2021 at 13:44

1 Answer 1

1

You can use variable content substitution syntax in bash to "arrange" one argument in several substring. The first substring is -- (that you're already removing) the second substring will be the variable name, the third will be = and the last will be the variable content.

This can be done by a slight modification to your script:

while [ $# -gt 0 ]; do

        if [[ $1 == *"--"* ]]; then
                param="${1/--/}"
                value="${param##*=}"
                param="${param%%=*}"
                declare $param="$value"
                echo variable name: $param 
                eval echo variable content: '$'"$param"
        fi

        shift
done

This way, if I feed these parameters to the new script:

sh test.sh --name=myname --family=myfamily

I get the following output:

variable name: name
variable content: myname
variable name: family
variable content: myfamily
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.