michael
michael

Reputation: 110510

Fix if condition in shell script

I have these if conditions, but it has compile errors. How can I fix it?

if [ $DEVICE_ID == "" ]; then

I get error:

line 63: [: ==: unary operator expected


if [ 'ls -l Mytest*.log | wc -l' -eq 1 ]; then

i get error:

line 68: [: ls -l Kernel*.log | wc -l: integer expression expected

Upvotes: 0

Views: 232

Answers (2)

glenn jackman
glenn jackman

Reputation: 246744

If you're using bash, use double brackets for conditional expressions: they are smarter about unquoted variables

if [[ $DEVICE_ID = "" ]]; then ...

would work (note: = instead of == for plain string equality instead of pattern matching)

For presence of files use an array

shopt -s nullglob
files=( *.log )
if (( ${#files[@]} > 0 )); the. Echo "there are log files"; fi

Upvotes: 1

William Pursell
William Pursell

Reputation: 212198

Quote the variable:

if [ "$DEVICE_ID" == "" ]; then

But it would be better to do:

if [ -z "$DEVICE_ID" ];

The second error is that you need to use backquotes:

if [ $(ls -l Mytest*.log | wc -l) -eq 1 ]; then

Upvotes: 3

Related Questions