I am just new to programming in Unix and have a small issue that I am unsure of how to solve. The objective of this piece of my script is to offer the user various options as to the type of scan they would like to use. This scan detects duplicate files with specified variables depending on the option chosen.
I am unable to get it working at all and am unsure why?
Also could you please offer me advice on how I could better display the selection screen if possible. I have only pasted part of my code as I would like to figure out the rest of my objective myself.
#!/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
It would help if you included the error messages you were receiving. When I tried this, I got an error of:
This makes the problem fairly clear. The
[operator in theifstatement is, in Unix’s “never use something complicated when some simple hack will work” style, just another program. (Seels /bin/[for proof!) As such, it needs to be treated like any other program with command-line options; you separate it from its options with whitespace. Otherwise, bash will think that “[$choice”, concatenated, is the name of a program to execute and will try to execute it. Thus, that line needs to be:After I changed that, it worked.
Also, as a style suggestion, I’d note that the
caseconstruct is a much easier way to write this code than usingifstatements, when you’ve got more than one test. And, as noted in other answers, you should put"marks around$choice, to guard against the case where the user input is empty or contains spaces —$choice, unquoted, will expand to a list of zero or more tokens separated by whitespace, whereas"$choice"always expands to a single token.