0

Can someone explain me what does the following script?

#!/bin/bash
for F in *.txt; do
  K=`grep abc $F`
  echo $K
  if ["$K" != ""]; then
        echo $F
  fi
done

I tested it and when it finds a txt file that contains the "abc" string, on prompt appears

`"./a.sh: line 5: [abc: command not found"`

error, otherwise appears the name of txt file that doesn't contain the "abc" string.

4 Answers 4

2

You're getting [abc: command not found because you don't have space after [ and before ] in your if condition.

You don't even need a for loop, you can use grep -l:

grep -l 'abc' *.txt
Sign up to request clarification or add additional context in comments.

Comments

1

The script is supposed to iterate over all ".txt" files in the current directory, grep them for abc, echo the result, and if the string was found, print the file name. However, it has a syntax error (you need spaces around [ and ]), breaks on file names with whitespace and is also more complex than needed. A better version is:

#!/bin/bash
for F in *.txt; do
  grep abc "$F" && echo "$F"
done

Comments

0

Leave a space after [ and a space before ] to resolve the errors:

#!/bin/bash
for F in *.txt; do
  K=`grep abc $F`
  echo $K
  if [ "$K" != "" ]; then
        echo $F
  fi
done

Comments

0

Your script goes through all the .txt files in the current directory to search for a pattern and displays the file name where it is matched. Refer to this tutorial http://www.tutorialspoint.com/unix_commands/grep.htm

Your code has a syntax error here

if ["$K" != ""]

You need to put a space after [ and before ] hence use this

if [ "$K" != "" ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.