Jasper
Jasper

Reputation: 139

Command Line Parameters not working properly

I'm trying to get this script working properly. When I'm executing this bash-script with:

./parameters.sh -name="Jonathan" -id="1" 

I'm getting the output: -id 1

I'm expecting an output like: Jonathan 1

#!/bin/bash

global=$*

function parameters() {
    for arguments in $global; do
        name=$(echo "$arguments" | cut -f1 -d=)
        value=$(echo "$arguments" | cut -f2 -d=)
        case "$name" in
            -name)    name=$value;;
            -id)      id=$value;;
            *)        echo "This parameter is not reconized."
        esac
    done

    echo "$name"
    echo "$id"
}

parameters

What do I have to change after the pipe inside the cut to make it working?

name=$(echo "$arguments" | cut -f1 -d=)
value=$(echo "$arguments" | cut -f2 -d=)

Upvotes: 0

Views: 269

Answers (1)

Cyrus
Cyrus

Reputation: 88583

I suggest with bash:

#!/bin/bash

global=$*

parameters() {
    for arguments in $global; do
        [[ "$arguments" =~ (.*)=(.*) ]]
        option="${BASH_REMATCH[1]}"
        value="${BASH_REMATCH[2]}"

        case "$option" in
            -name)    name="$value";;
            -id)      id="$value";;
            *)        echo "This parameter is not reconized."
        esac
    done

    echo "$name"
    echo "$id"
}

parameters

Upvotes: 1

Related Questions