How to pass a string parameter on bash function?

10,968

Solution 1

Quoting: In short, variables are not replaced with their values inside 'single-quoted' strings (aka. "variable substitution"). You need to use any one of "double quotes", $'dollar quotes', or

<<EOF
here strings
EOF

Solution 2

As l0b0 pointed, you can't use single quotes here. Apart from that, in your example you don't have to use sed either. It looks far cleaner with grep:

get_parameter ()
{
   echo "$query" | grep -o "${1}=[^&]*" | sed "s/%20/ /g"
}

Without echo:

get_parameter ()
{
   <<< "$query" grep -o "${1}=[^&]*" | sed "s/%20/ /g"
}

And finally, without the second sed (just bash):

get_parameter ()
{
   <<< "${query//%20/ }" grep -o "${1}=[^&]*"
}
Share:
10,968
michelemarcon
Author by

michelemarcon

Hello, I'm a Java software engineer. I also have some Android and Linux experience.

Updated on September 18, 2022

Comments

  • michelemarcon
    michelemarcon over 1 year

    I have this code that does work:

    get_parameter ()
    {
       echo "$query" | sed -n 's/^.*name=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
    }
    

    But I want to replace the "name" with the parameter that I pass to get_parameter

    get_parameter ()
    {
       echo "$query" | sed -n 's/^.*$1=\([^&]*\).*$/\1/p' | sed "s/%20/ /g"
    }
    NAME=$( get_parameter name )
    

    This however, doesn't work. Where am I wrong?

  • they
    they over 2 years
    Note that you are leaving $1 unquoted in the shell.
  • Abdelazeem Kuratem
    Abdelazeem Kuratem over 2 years
    @they I know and that is the right way to write it!! Also, I am already using it with the same syntax, so you might misunderstand it!!
  • they
    they over 2 years
    To quote the expansion of $1 in your command, use sed -n 's/^.*'"$1"'=\([^&]*\).*$/\1/p' | sed "s/%20/ /g". Test your command with $1 set to the string 1 2 3. Then also test with * and / and add a caveat to you answer about how $1 would be interpreted as a regular expression, and that it can't contain the delimiter used with the substitution command, and what to do instead.