-1

For example:

#!/bin/bash
DIR=`dirname $0 `
Save_DIR="Save"
cd $DIR 

if  [ -d $Save_DIR ];then
     rm  $Save_DIR/*
else
     mkdir  $Save_DIR
fi

 for  i  in  $(ls)
 do
     if  [  $i==$Save_DIR ]
     then
         echo "is same "
     fi
 done

I think right result is a line 'is same', but we I run it

is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 
is same 

It seem the code if do nothing, why?

Gerald Schneider
  • 17,416
  • 9
  • 60
  • 78
Yong Deng
  • 61
  • 1
  • 1
  • 5

1 Answers1

1

This necessarily is doing the test [ -n $i==$Save_DIR ], testing if the string is non-empty, because you have not provided any spaces around =.

you need to do:

[ "$i" = "$Save_DIR" ]

== is bash-ism, but [ is not so you should use = instead, but would work if you are using bash. Quote variables while using [ to prevent word splitting and filename expansion.

Also don't parse ls, you can easily use shell globbing here like:

for i in *

To match only directories:

for i in */
heemayl
  • 39,294
  • 7
  • 70
  • 76