讀取檔案的第一行並將其與 shell 檔案中的字串進行比較

讀取檔案的第一行並將其與 shell 檔案中的字串進行比較

我需要讀取文件的第一行並將其與文字匹配。如果文字匹配,我需要執行某些操作。

問題是命令是否無法將變數與字串進行比較。

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

if 區塊不起作用。我認為我在第一行中捕獲的值存在一些問題。

答案1

第一行很可能包含不可列印的字元或前導或尾隨空白或空格以外的空白字元(在傳遞給 時忘記引用變數echo)。您也可以先清理它:

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

相關內容