开发者

String comparision not working in shell script

I have written a simple shell script to do some automation work. Basically the script searches for all the fil开发者_开发技巧es in the current path and if the file is a specified one, it does some action. Below are the relevant lines ---

#!/bin/bash
for i in `ls *`
do
if [$i =="ls.sh"] 
then .... //do something
fi
done

However, the string comparision in line 3 is not working and I am getting this when I run the script --

./ls.sh: line 3: [scripth.sh: command not found
./ls.sh: line 3: [scripth.sh~: command not found
./ls.sh: line 3: [test.sh: command not found

What is the correction to be done ?


first of all, don't use ls like that. It will go bonkers if your files have spaces!. Use shell expansion. Then, you can use case/esac to make string comparison. (or if/else)

for file in *
do
  case "$file" in
    "ls.sh" ) echo "do something"
     ;;
  esac
done


There are several problems.

In line 1, you are not doing what you think you are. You should put a backquote around ls *:

for i in `ls *`

That will go through all files that list in the current directory. Your line will not run any command, but instead it will use * to get all files and your list will include a word "ls" at the front.

try this from a command line:

echo ls *
echo `ls *`

You might just want to do:

for i in *

Second problem. Put spaces inside your square brackets:

[ $i == "ls.sh" ]

The spaces are necessary.

Third problem. Use one = for string comparison

[ $i = "ls.sh" ]


Use: if [ "$i" = "ls.sh" ] - notice the spaces.


If you only want to check the existing of a file, you could do it directly in shell.

if [ -e ls.sh ]
then 
  # ... do something
fi


You have not included a space after ==, so your code should actually be:

#!/bin/bash
for i in `ls *`
do
    if [ $i == "ls.sh" ] 
    then 
        //do something
    fi
done
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜