Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arguments with space when parsing input parameters for bash script

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
like image 306
AnOldSoul Avatar asked Nov 23 '25 09:11

AnOldSoul


1 Answers

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

like image 61
that other guy Avatar answered Nov 24 '25 22:11

that other guy