【问题标题】:egrep is returning 0 in bash script but executing manually the command returning correct value | unix bashegrep 在 bash 脚本中返回 0 但手动执行返回正确值的命令 | Unix 重击
【发布时间】:2017-11-07 17:51:52
【问题描述】:

我正在执行一个 bash 脚本,如果 ftp 连接失败或使用 egrep 成功,则返回我,问题是当我尝试使用 egrep 获取单词时返回 0 但如果我手动执行命令则返回2.

这是我的代码:

#Create the FTP Connection.
for ip_address in ${IP_ADDRESS[@]}; do
  ftp ${ip_address} <<ftp_commands > ${FTP_RESULTS}
  user "${USER_ID}" "${USER_PASSWORD}"
  pwd
  bye
ftp_commands

ftp_result_id=`egrep -c "Login failed|Connection refused|Not connected|Connection timed out" ${FTP_RESULTS}`

if [ ${ftp_result_id} -gt 0 ]; then
    echo "$(date +%m/%d/%y_%H:%M:%S) - ${ip_address} - Not connected" >> ${CONNECTION_RESULTS_FILE}
else
    echo "$(date +%m/%d/%y_%H:%M:%S) - ${ip_address} - Connected" >> ${CONNECTION_RESULTS_FILE}
fi

done

ftp_results_id 在 egrep -c 命令中返回 0,但我在运行后手动执行并创建文件“FTP_RESULTS”并且正在工作,假设找到 2 个匹配“未连接”

有什么建议吗?

【问题讨论】:

  • 使用grep -Eq,然后使用退出代码
  • @anubhava grep -Eq 没有返回任何东西...
  • 像所有命令一样,它返回一个有用的退出代码。 if grep -Eq "your terms" yourfile; then echo "It had matches"; fi
  • 能否将错误写入stderr? 2&gt; ${FTP_RESULTS} 可以工作吗?
  • 我不得不使用嵌套的 if,这对我来说是这样的

标签: bash shell unix ftp grep


【解决方案1】:

egrep -c 命令对匹配进行计数。 然后,如果有超过 0 个匹配项,则使用条件执行某些操作。

更简单更好的解决方案是使用退出代码egrepegrep 如果找到匹配项,则以 0(= 成功)退出, 否则非零。 您可以像这样编写if 语句:

if egrep -q "Login failed|Connection refused|Not connected|Connection timed out" "${FTP_RESULTS}"; then

这相当于您发布的代码中的逻辑。 不需要ftp_result_id 变量。 并且不需要保存egrep 的输出。 我添加了-q 标志,以便egrep 不会产生任何输出。 不需要。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2021-04-28
    • 1970-01-01
    • 2019-11-14
    • 2010-11-25
    • 2014-11-22
    相关资源
    最近更新 更多