Toren
Toren

Reputation: 6856

logical expression in bash

The purpose of the script is go over file contains list of directory names and append to other file directory names that are not exist in.

#!/bin/bash
FILES="list.txt"
2nd_file="2nd_list.txt"
for f in $FILES
do
    # if  backup dir exists, read next dir
if [ /bin/grep -q $f $2nd_file ]
then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no file exists
    echo "$f" >>$2nd_file
done

I getting errors in if expression.

I understood what your answers about and changed the script :

 #!/bin/bash
 FILES="list.txt"
 2nd_file="2nd_list.txt"
 for f in $FILES
 do
        # if  backup dir exists, read next dir
 /bin/grep -q $f $2nd_file
 if [ $? -eq 0 ]
 then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no dir exists
     echo "$f" >>$2nd_file
done

But now a small problem that script doesn't read directory names from FILES

Output is :

 Skiping list.txt file...

Upvotes: 0

Views: 237

Answers (2)

hmontoliu
hmontoliu

Reputation: 4019

your if expression should be:

if  /bin/grep -q $f $2nd_file

without square brackets

EDITED as you edited your post:

Your script should be:

#!/bin/bash
FILES="list.txt"
2nd_file="2nd_list.txt"
for f in $(cat $FILES) # see the modification
do
    # if  backup dir exists, read next dir
if /bin/grep -q $f $2nd_file # see the modification
then
    echo "Skiping $f file..."
    continue  # read next file
fi
    # we are hear means no file exists
    echo "$f" >>$2nd_file
done

The modifications I've made are:

  • in the "for": you need the content of $FILE archive, not the string "list.txt" (the value of $FILES variable) so you have to dump those contents with cat or with a "<" (ie: while read f; do ... ; done < $FILES)

  • in the if statement: you have to evaluate a command. The command is you grep. If grep returns 0 then your "if" stuff will be done; any other return value will skip your if statement. (that's like your useless check of the return status but more efficient)

Upvotes: 2

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

[ is a command. If you're trying to use grep as the command, then don't use [.

Upvotes: 1

Related Questions