0

I am working on a shell script where it has to extract string from parameter passed. If I am passing parameters like

      test.sh arg1=someArgument Arg2=AnoTherArgument

Assume user may pass the arguments with the name and value in any case,

I have to extract the parameters and manipulate, some thing like

      for arg in "$@"
      do
          if [ lower("${arg}") == "arg1" ] then
                # extract arg1's value and do something
          elif [ lower("${arg}") == "arg2" ] then
                # extract arg2's value and do something
          fi
      done

Please help me how can I extract the parameter's value in the same case that was passed?

2
  • 1
    It isn't valid POSIX to use == inside of [ ]; use a single equals sign, =, instead. Also, which shell and version are you targeting? bash 4 has parameter expansion operators built-in for converting variables to lower and upper case, without the need for external tools such as tr. Commented Jul 25, 2012 at 12:41
  • you should not change your question, because the title would not be coherent, accept the answer if it solves your problem Commented Jul 25, 2012 at 12:43

3 Answers 3

3

For clarity, I prefer a case statement like this:

while [ $# -gt 0 ]
do
    case $1 in
    a=* ) echo ${1#a=};;
    b=* ) echo ${1#b=};;
    # etc
    esac
    shift
done
Sign up to request clarification or add additional context in comments.

3 Comments

I have edited the post. Please have a look. The arguments name passed can be of any type. If so I can convert the argument to lowercase using tr [:upper:] [:lower:], but how can I extract the value of argument with the same case the user has passed ? Please help me.
[Aa][Rr][Gg]1) echo ${1#[Aa][Rr][Gg]1};;
Do just the same: convert only the first part of each argument with tr [:upper:] [:lower:], maybe like this (assuming only one equal sign per argument): case $(echo ${1%=*} | tr [:upper:] [:lower:]) in; arg1 ) echo ${1#*=};; ; esac (Sorry for the bad display)
0

Use double bracket to match glob pattern ; semicolon is needed before "then"

if [[ "$arg" = a=* ]];then echo ${arg#a=};fi

or

if [ "${arg%%=*}" = a ];then echo ${arg#a=};fi

for more information

man bash
/Parameter Expansion

1 Comment

I have edited the post. Please have a look. The arguments name passed can be of any type. If so I can convert the argument to lowercase using tr [:upper:] [:lower:], but how can I extract the value of argument with the same case the user has passed.
0

Why bother working to parse arguments? Pass things through the environment:

In foo:

#!/bin/sh
echo Value of arg1: ${arg1-default value}

Then:

$ arg1=blah ./foo
Value of arg1: blah

and

$ ./foo
Value of arg1: default value

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.