【问题标题】:If statement don't works in sh file如果语句在 sh 文件中不起作用
【发布时间】:2020-10-18 14:41:04
【问题描述】:

美好的一天。

我想用 linux 和 bash 自动化某些过程。我陷入了一个 IF 语句。

这是代码:

#!/bin/bash
result=$(
 sqlplus -s /nolog << EOF
 CONNECT admin/password@server;

 whenever sqlerror exit sql.sqlcode;
 set echo off
 set heading off
 @processQuery.sql
 exit;
 EOF
)
echo $result
if [ "$result" != "no rows selected" ]
then echo "Please, clean up"
else echo "All Ok"
fi

输出是:

no rows selected
Please, clean up

非常感谢您的帮助。

更新:添加

result2=${result:1}

if [ "$result2" != "no rows selected" ]

非常感谢您,特别感谢 @mercury0114 的回答!

【问题讨论】:

  • 你的问题是什么?
  • 字符串末尾不包含空格吗?
  • echo ${result@Q} 看起来像什么? (使用bash,应该显示result 中是否有额外的字符)
  • @noam 我的问题是为什么我没有得到预期的结果。
  • @Yuji 当我尝试echo "."$result"." 我得到. no rows selected. 但是当我把它放在 IF 语句中返回相同的错误结果。

标签: bash if-statement sh heredoc


【解决方案1】:

您确定您的result 变量不包含空格或其他内容吗? 因为对我来说以下代码:

#!/bin/bash
result="no rows selected"
echo $result
if [ "$result" != "no rows selected" ]
then echo "Please, clean up"
else echo "All Ok"
fi

打印

no rows selected
All Ok

我会仔细检查 SQL 查询返回的内容。

另外,考虑用简单的result 替换"$result"

if [ result != "no rows selected" ]

【讨论】:

  • 我尝试使用 echo "."$result"." 并得到:. no rows selected. 我输入 " no rows selected" 得到相同的结果。使用result 支持$result 没有变化。谢谢。
  • @EnriqueLorenzoVillarMavila 那么为什么.n 之间有空格?不应该是.no rows selected.吗?
  • 是的。我不知道为什么会出现那个空格,但是 IF 语句没有变化。也许我需要转换 SQLPLUS 的输出,但我不知道如何。
  • 去掉第一个空格做"${result:1}"
猜你喜欢
  • 2015-04-23
  • 2018-10-12
  • 2012-12-26
  • 2013-06-20
  • 2013-09-04
  • 2014-09-10
  • 2018-02-15
  • 1970-01-01
相关资源
最近更新 更多