scriptz
scriptz

Reputation: 515

function fails but works at cli as oneliner

This function I ripped off and hacked for my purposes:

function chkUrl () {
urlRegex="(https?|ftp|file)://[-A-Za-z0-9\+&@#/%?=~_|!:,.;]*[-A-Za-z0-9\+&@#/%=~_|]"

    url="$1" ; notSend "$LINENO" "url" "$url" "tn"
    #url="http://cloud0.storagedump.com/e7f8630b74678c157f37998a1f7e5151" #; notSend "$LINENO" "url" "$url" "tn"

    if [[ ! "$url" =~ "$urlRegex" ]] ; then 

            exit "$LINENO"

    fi
}

to validate that a URL entry appears good, before doing anything online, is erroring in a script and I can't see why. But entered at the cli as a oneliner, the commands run fine when fed the same URL that fails in the function.

I feel certain I am just making some obvious blunder that is not all too obvious to me atm if anyone can show me what it might be.

Upvotes: 0

Views: 44

Answers (2)

konsolebox
konsolebox

Reputation: 75478

For an expression to be recognized, it should not be enclosed around double quotes:

if [[ ! "$url" =~ $urlRegex ]]; then 

Also, exit would make the script exit. If you want to return a code from the function, use return

return "$LINENO"

Also note that in shell scripts, a "true" return value for a command is zero while "false" (has errors) is any nonzero. Try true; echo $? and false; echo $?

Upvotes: 2

SzG
SzG

Reputation: 12619

Native shell regex is a feature of Bash 4.x. Your oneliner probably works because you run it in your interactive shell, which is Bash 4.x.

If you put it in a shell script, with shebang #!/bin/sh you're left with POSIX sh functionality. No native regexes.

Try #!/bin/bash as the shebang first.

Upvotes: 1

Related Questions