Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Unexpected operator" error when comparing strings in shell script [duplicate]

Tags:

linux

shell

I'm trying to create a shell script that runs a command and plays music if the output of running the other script is nonempty. So far, I have this. However, I keep getting "Unexpected operator" errors on the last line. What is the issue with the code?

As an additional note, I've verified that myscript works fine, and running vlc from the command-line like that works as well.

#!/bin/sh

TOF=`myscript | cat`
EMPTYSTR=""

if [ "$TOF" == "$EMPTYSTR" ]; then
    echo "vlc somemusicfile.mp3"
fi
like image 356
eqb Avatar asked Jan 30 '26 13:01

eqb


2 Answers

Testing for string equality works using =. (As a matter of fact, equality is wrong here. You'd want to use inequality). However, you could simply use -n "$TOF" to check for a non-empty string.

Also, using |cat is unnecessary.

like image 56
fnl Avatar answered Feb 01 '26 05:02

fnl


test -z "$(myscript)" || echo "vlc somemusicfile.mp3"

(though I don't know what's wrong with your code, maybe I'm missing some bashism, you can try changing #!/bin/sh to #!/bin/bash).

like image 35
Michael Krelin - hacker Avatar answered Feb 01 '26 04:02

Michael Krelin - hacker



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!