Search code examples
bashfunctioncurlgrepcut

Use grep and cut inside a bash function


i have the following bash code:

function () {
   curl="$(curl -s "$2" >> "$1")"
   version="$(grep '$3' $1 | $4 )"
   echo $version
}

function "test" "https://google.com" "String" "cut -d' ' -f3 | cut -d'<' -f1"

Basically the function downloads the page and then uses grep to look for a specific string. After that "cut", cuts down the results further. But ... unfortenatly the cut inside the function doesn't work. I only get the following output:

"usage: cut -b list [-n] [file ...]
       cut -c list [file ...]
       cut -f list [-s] [-d delim] [file ...]"

Maybe i overlooked something ... or maybe you have a better idea :-)


Solution

  • Since $4 contains shell metacharacters that aren't processed when expanding variables, you need to use eval to execute it.

    Also, you need to put $3 in double quotes, not single quotes, otherwise the variable won't be expanded.

       version="$(grep "$3" "$1" | eval "$4" )"