Leo
Leo

Reputation: 189

null check throws unary operator error

I am tying to check if a variable is null, It throws the below error. I have tried the below combinations but it says the same error. I am trying to find out the files in a folder

cmd="ls -tm"
output=$($cmd)

echo $output // doesn't print out anything as the folder is empty

if [  $output != "" ];

For the below one it goes to the loop

if[ -z $output ];

Error output:

line 25: [: !=: unary operator expected

Any suggestions for handling this?

Upvotes: 0

Views: 190

Answers (2)

rojomoke
rojomoke

Reputation: 4025

To expand on @Quine's suggestion, if $output is null, your if statement expands to

if [ != "" ];

which makes bash think an argument is missing. Quoting the parameter name overcomes this.

Upvotes: 1

Quine
Quine

Reputation: 158

Have you tried using if [ "$output" != "" ]; instead of if [ $output != "" ];?

Upvotes: 2

Related Questions