Hi I am tryibg to check for presance of a string in a big string. I tried as follows:

IS_VECTOR_TEST_CASE=`grep AIV "$PWD"`
if [ "$IS_VECTOR_TEST_CASES" = "" ]
then
   #do something
else
   #do something
fi

This always giving me as if [ "$IS_VECTOR_TEST_CASES" = "" ] is true with following error:
grep: /abc/bcd/cde/AIV/def: Invalid argument

Please help me in this issue...

Dani AI

Generated

The failure here is two-fold: the command is invoking grep with "$PWD" as a filename (so grep tries to open a directory and errors), and the script checks the wrong variable name (IS_VECTOR_TEST_CASES vs the variable actually set). That explains the "Invalid argument" from grep and why the test always looked empty. was right that feeding a string into grep is one way, but using a shell builtin is simpler and faster when you just need a substring test.

A few safe ways to check whether a shell variable contains "AIV":

# bash/ksh: builtin pattern match (fast, no fork)
if [[ "$mystring" == *AIV* ]]; then
  # found
fi
# POSIX-compatible: case statement (works in /bin/sh)
case "$mystring" in
  *AIV*)  # found ;;
  *)      # not found ;;
esac
# Using grep when you want its features; use -F for fixed string, -q for quiet exit status
if printf '%s\n' "$mystring" | grep -Fq 'AIV'; then
  # found
fi

Practical tips: always quote variables to avoid word-splitting, prefer $(...) over backticks for command substitution, and use -F if the pattern may contain regex metacharacters. Choose [[ ... ]] or case for pure substring checks (they avoid forking grep). If scanning a path like $PWD for a component, treat it as a string (pattern match) rather than passing the directory name to grep as a file. For reference on grep and shell pattern matching see the GNU grep manual and the Bash pattern-matching docs: GNU grep manual and Bash pattern-matching.

Recommended Answers

All 2 Replies

echo "string" | grep "pattern"

Thnq Very much.........

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.