Anatoly Rapoport
Anatoly Rapoport

Reputation: 11

Bash Function help, Empty output

I'm trying to write this function that searches for vowels in string

x="A\|E\|I\|O\|U\|a\|e\|i\|o\|u"


string () {
        if echo $1 | grep -q $x
        then
        echo $1 | tr -d $x
        fi
}

string

When i run it, it returns empty string

I have tried to recreate this with out function and it worked

x="A\|E\|I\|O\|U\|a\|e\|i\|o\|u"


if echo $1 | grep -q $x
then
echo $1  | tr -d $x
fi

No function:

root@ubuntu-2gb-fra1-01:~# bash test2.sh "This website is for losers LOL!"
Ths wbst s fr lsrs LL!

With function:

root@ubuntu-2gb-fra1-01:~# bash test.sh "This website is for losers LOL!"
root@ubuntu-2gb-fra1-01:~#

Can anyone explain to me what's the reason? Thanks

Upvotes: 0

Views: 274

Answers (3)

tripleee
tripleee

Reputation: 189387

You don't need grep or tr for this.

string () {
    case $1 in
     *[AEIOUaeiou]*)
        echo "${1//[AEIOUaeiou]/}";;
     *) echo "$1";;
    esac
}

But of course, the substitution does nothing if the string doesn't contain any of those characters, so all of this can be reduced to

string () {
    echo "${1//[AEIOUaeiou]/}"
}

The case statement is portable all the way back to the original Bourne shell, but the ${variable//pattern/replacement} syntax is specific to Bash.

Call it like string "$1" to run it on the script's first command-line argument.

Upvotes: 0

user1934428
user1934428

Reputation: 22225

You run your function string without parameters. Hence inside string $1 is always empty and the condition is never met.

You can for instance call it as

string "$1"

to forward the current first argument to your function.

Upvotes: 1

mirek
mirek

Reputation: 111

You need to add following line at the beginning of your code:

i=$1

and change the reference of variable in function from $1 to $i.

Upvotes: 0

Related Questions