0

I need to read first line of a file and match it with a text. If the text matches, I need to do certain operation.

Problem is if command is unable to compare the variable with the string.

file_content=$(head -1 ${file_name})
echo $file_content
if [[ $file_content = 'No new data' ]]; then
    echo "Should come here"
fi
echo $file_content
if [ "${file_content}" = "No new data" ]; then
  echo "Should come here"
fi

The if block is not working. I think the value that I am capturing in line 1 has some issues.

Rui F Ribeiro
  • 56,709
  • 26
  • 150
  • 232

1 Answers1

1

Most likely the first line contains non-printable characters or leading or trailing blanks or blank characters other than space (you forgot to quote the variable when passed to echo). You could also clean it up first:

content=$(
  sed '
    s/[[:space:]]\{1,\}/ /g; # turn sequences of spacing characters into one SPC
    s/[^[:print:]]//g; # remove non-printable characters
    s/^ //; s/ $//; # remove leading and trailing space
    q; # quit after first line' < "$file_name"
)

if [ "$content" = 'No new data' ]; then
  echo OK
fi