3

I wrote a bash script which takes parameters by name and read its value in key value pairs. Below is an example of how I run my script.

 sh test.sh param1='a' param2='b'

I then refer the input arguments like $param1 and $param2 inside my script. Below is the script I wrote to do this.

for item in $@; do
case $item in
(*=*) eval $item;;
esac
done

But when there is space in the value of the argument, it takes only the part before the space.

 param3='select * from'

would only assign 'select' to param3 and not the whole string. How can I achieve this? Any help would be much appreciated.

EDIT :

After Inian's answer

for item in $@; do
case "$item" in
(*=*) eval "$item";;
esac
done
2
  • 1
    Have you considered passing them in as variables instead, i.e. param1='a' param2='b' sh test.sh instead? This will make echo "$param1" available immediately without parsing Commented Jan 10, 2017 at 3:24
  • 1
    Using $@ or $* without enclosing in double quotes is not a good idea. It would misbehave when your strings have special characters in them, like whitespace and wildcards. Commented Jan 10, 2017 at 3:26

1 Answer 1

6

You can do this by quoting "$@" and using declare instead of eval:

for item in "$@"; do
case $item in
(*=*) declare "$item" ;;
esac
done

However, this is now a bash script, so you have to run it with bash test.sh and not sh test.sh

Sign up to request clarification or add additional context in comments.

3 Comments

That did the trick! but as you have indicated in the comment, what is the difference between specifying parameters after "sh <scriptName>" and before "sh <scriptName"> ? sorry I am new to this.
@mayooran: if you specify them before the command, they're interpreted as environment variable assignments by the calling shell, so they're directly available in the script. If you put them after, they're interpreted as strings to pass to the script as $1, $2, etc, and then you have to do something nonstandard and weird to turn them into variable assignments. The normal way for scripts to take arguments is either as bare strings in a standard order (e.g. sh test.sh val1 val2), or use - options to specify them (e.g. sh test.st -a val1 -b val2).
@GordonDavisson oh, got it mate! thanks a lot! :) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.