0

Suppose I have one file input.txt in which the data is written each in new line like

JAVA

PERL

I have written one shell script which will read the file content line by line and then create the folder with the name written in the file and .As I need to do some other action on the basis of content read from the file also ,so I put if condition.

#!/bin/sh
while read -r line
do
if [[$line=="JAVA"]];then
cd /tmp/Repo
mkdir $line
*some copy command*
 fi
if [[$line=="PERL"]];then
cd /tmp/Repo
mkdir $line
*some copy command*
fi
done < input.txt

But I am getting the below error as mentioned:-

./files.sh: line 4: [[JAVA==JAVA]]: command not found

./files.sh: line 4: [[PERL==JAVA]]: command not found

Can anyone please help me in debugging the shell script what should be the correct syntax .

  • `[[` is a **command**. Like every other command, it needs to be separated from its arguments with spaces. – Charles Duffy Aug 01 '16 at 21:59
  • You need to put in some whitespace so bash can tell which tokens are what: `if [ $line == "JAVA" ]` – Juan Tomas Aug 01 '16 at 21:59
  • @JuanTomas, if using `[` rather than `[[`, then you need quotes, and should be using `=` rather than `==`, thus `if [ "$line" = "JAVA" ]`. – Charles Duffy Aug 01 '16 at 22:00
  • 1
    @JuanTomas, see http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html re: `=` vs `==` (you'll note that the POSIX standard only specifies the former). – Charles Duffy Aug 01 '16 at 22:00
  • Thanks Charles, I'll have a look at that. I only ever used `[` before. The `==` is just some cruft from using a lot of other languages. – Juan Tomas Aug 01 '16 at 22:02
  • ...similarly, `if [ $line == "JAVA" ]` is prone to unexpected behavior depending on how many words the contents of `line` expand to. If it's empty, that'll become `if [ == JAVA ]`, which will lead to a syntax error from the `test` command; hence, the need to quote the expansion (`"$line"`) -- whereas the constant `JAVA` will only ever be one word, and thus doesn't need to be quoted. – Charles Duffy Aug 01 '16 at 22:03
  • *prone to unexpected behavior* Understood. Been there, done that. – Juan Tomas Aug 01 '16 at 22:05

1 Answers1

0

Whitespace!

if [[ $line = JAVA ]]; then

...or...

# need to quote all expansions if using [ ] rather than [[ ]]
if [ "$line" = JAVA ]; then

BTW, consider using a case statement instead of mucking around with if/else at all::

case $line in
  JAVA) ...java-handling code here... ;;
  PERL) ...perl-handling code here... ;;
esac

There are other errors in this script as well; please see http://shellcheck.net/ for a full report.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441