shell中if和else语句的错误

Joe*_*jie 1 bash shell

我刚接触Unix中的编程,并且有一个小问题,我不确定如何解决.我的这个脚本的目的是为用户提供各种选项,使他们想要使用的扫描类型.此扫描根据所选的选项检测具有指定变量的重复文件.

我根本无法让它工作,我不确定为什么?

另外,如果可能的话,请您就如何更好地显示选择屏幕向我提供建议.我只粘贴了部分代码,因为我想自己弄清楚其余的目标.

#!/bin/bash
same_name="1"
filesize="2"
md5sum="3"
different_name="4"
echo "The list of choices are, same_name=1, filesize=2, md5sum=3 and different name=4"
echo "Search for files with the:"
read choice 
if [$choice == "$same_name" ];then
find /home/user/OSN -type f -exec basename '{}' \; | sort > filelist.txt
find /home/user/OSN -type f -exec basename '{}' \; | sort | uniq -d > repeatlist.txt
else
ls -al /home/user/OSN  >2filelist.txt
fi
Run Code Online (Sandbox Code Playgroud)

msw*_*msw 5

shell命令[也称为test需要一个空格,以便shell正确解析.例如:

if [ "x$choice" == x"$same_name" ] ; then
Run Code Online (Sandbox Code Playgroud)

相当于

if test "x$choice" == "x$same_name" ; then
Run Code Online (Sandbox Code Playgroud)

在变量前加上"x"是一种成语,可以防止test看到太少的参数.如果称为测试会抱怨test 5 ==,所以如果$choice$same_name是空的调用expr是语法正确.

您还可以使用构造${choice:-default}${choice:=default}防止unset或null shell变量.