user4794392
user4794392

Reputation:

grep command in Bash

I've written the following function in Bash:

function findTest {
 files=`ls $1`
 for file in ${files[*]}; do
    if [[ "$file"=="*.tst" ]]; then
        grep "version: $2" $1/$file
        if [[ $? -eq 0 ]]; then
            echo -n $2
            grep "result" | cut -d ":" -f2 
        fi
    fi  
 done
}

for some odd reason, the line grep "version: $2" $1/$file claims that $1/$file isn't a file/directory, yet I know for a fact that $1 contains an address of directory which $file exsists in. Is there any rational reason why

Upvotes: 1

Views: 577

Answers (2)

Etan Reisner
Etan Reisner

Reputation: 80931

There are a number of issues with the snippet as posted.

http://www.shellcheck.net finds many of them.

 1  function findTest {
 2   files=`ls $1`
             ^––SC2006 Use $(..) instead of legacy `..`.
                 ^––SC2086 Double quote to prevent globbing and word splitting.
 3   for file in ${files[*]}; do
 4      if [[ "$file"=="*.tst" ]]; then
                ^––SC2077 You need spaces around the comparison operator.
                       ^––SC2140 The double quotes around this do nothing. Remove or escape them.
 5          grep "version: $2" $1/$file
                                 ^––SC2086 Double quote to prevent globbing and word splitting.
                                    ^––SC2086 Double quote to prevent globbing and word splitting.
 6          if [[ $? -eq 0 ]]; then
 7              echo -n $2
                          ^––SC2086 Double quote to prevent globbing and word splitting.
 8              grep "result" | cut -d ":" -f2 
 9          fi
10      fi  
11   done
12  }

The things it doesn't find are things like Why you shouldn't parse the output of ls(1) and that files isn't an array like you appear to have been trying to create or that ${files[*]} (assuming it was an array) would be less useful than "${files[@]}" since the * version (quoted or not) doesn't handle files with spaces in the names, etc.

Upvotes: 2

anubhava
anubhava

Reputation: 785146

Rather than trying to run ls and parse it's output better to use globbing and list files of a an extension in for loop:

findTest() {
  for file in "$1"/*.tst; do
      if grep -q "version: $2" "$file"; then
          echo "grep succeded"
      fi
  done
}

Upvotes: 2

Related Questions