Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bash, grep sentence from file

Tags:

bash

I have made a simple answering machine in bash. Basically if you greet it, it will greet you back but now I have a problem with sentence analyzing. If the sentence ($@) is more than one word, it fails.

if [[ "$@" = $(grep -Fx "$@" 'vocabulary/greeting') ]]
        then
            speak greeting
        elif [[ "$@" = $(grep -Fx "$@" 'vocabulary/appreciative') ]]

The output:

> hello
Sam:  Hi!
> how are you
grep: are: No such file or directory
grep: you: No such file or directory
grep: are: No such file or directory
grep: you: No such file or directory
grep: are: No such file or directory
grep: you: No such file or directory
grep: are: No such file or directory
grep: you: No such file or directory
grep: are: No such file or directory
grep: you: No such file or directory
Sam:  I don't understand.
> 

How do I fix this? How can I catch possible errors like these in the future?

like image 346
Corvo Avatar asked Apr 01 '26 09:04

Corvo


1 Answers

Use "$*" instead of "$@".

if [[ "$*" = "$(grep -Fx "$*" 'vocabulary/greeting')" ]]

"$*" is a string representation of the arguments, while "$@" is an array.

like image 198
Jahid Avatar answered Apr 04 '26 02:04

Jahid



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!