使用AND运算符Bash if语句

时间:2017-02-03 14:13:34

标签: bash if-statement and-operator

尝试与字符串变量进行比较,我根据https://unix.stackexchange.com/questions/67898/using-the-not-equal-operator-for-string-comparison的解决方案尝试了代码

class MySpider(CrawlSpider):
    name = 'dknews'
    start_urls = ['http://www.example.org/uat-area/scrapy/all-news-listing']
    allowed_domains = ['example.org']

    def parse(self, response):
        hxs = Selector(response)
        soup = BeautifulSoup(response.body, 'lxml')
        nf = NewsFields()
        ptype = soup.find_all(attrs={"name":"dkpagetype"})
        ptitle = soup.find_all(attrs={"name":"dkpagetitle"})
        pturl = soup.find_all(attrs={"name":"dkpageurl"})
        ptdate = soup.find_all(attrs={"name":"dkpagedate"})
        ptdesc = soup.find_all(attrs={"name":"dkpagedescription"})
         for node in soup.find_all("div", class_="module_content-panel-sidebar-content"):
           ptbody = ''.join(node.find_all(text=True))  
           ptbody = ' '.join(ptbody.split())
           nf['pagetype'] = ptype[0]['content'].encode('ascii', 'ignore')
           nf['pagetitle'] = ptitle[0]['content'].encode('ascii', 'ignore')
           nf['pageurl'] = pturl[0]['content'].encode('ascii', 'ignore')
           nf['pagedate'] = ptdate[0]['content'].encode('ascii', 'ignore')
           nf['pagedescription'] = ptdesc[0]['content'].encode('ascii', 'ignore')
           nf['bodytext'] = ptbody.encode('ascii', 'ignore')
         yield nf
            for url in hxs.xpath('//ul[@class="scrapy"]/li/a/@href').extract():
             yield Request(url, callback=self.parse)

这对我不起作用,我没有收到任何错误消息,就像跳过代码块一样。

我也按照这里的答案Bash if statement with multiple conditions

尝试了这样的
if [ "$ACTION" != "dry" ] && [ "$ACTION" != "prune" ]
then
    echo "Invalid"
fi

如果$ ACTION不是“干”,即使其“修剪”

,这也会回复“无效”

有什么建议吗?

修改

完整代码

if [[ "$ACTION" != "dry" && "$ACTION" != "prune" ]]
then
    echo "Invalid"
fi

2 个答案:

答案 0 :(得分:2)

好吧,在出现这种命令的大多数情况下,使用case提供了一个更易于维护的解决方案,因为在脚本的生命周期中,您将需要更改操作名称,处理新情况等等:

case "$ACTION" in 
  ("dry"|"prune") 
    : # Insert appropriate code
  ;;
  (*)
    echo Invalid
  ;;
esac

其次,在这种情况下不需要使用[[语法

if [ "$ACTION" != dry ] && [ "$ACTION" != prune ]; then
  echo Invalid
fi
在这种情况下,

就足够了。要测试一切是否按预期工作,您可以添加else分支:

if [ "$ACTION" != dry ] && [ "$ACTION" != prune ]; then
  echo Invalid
else
  echo Valid
fi

答案 1 :(得分:0)

<强>解决方案

根据@Dario的答案使用案例并在班次操作之后将检查移至使代码按预期工作。

OPTIND=1

while getopts "b:a:" option
do
    case "${option}"
    in
        b) MERGE_BRANCH=${OPTARG};;
        a) ACTION=${OPTARG};;
    esac
done

shift $((OPTIND-1))
[ "$1" = "--" ] && shift

(( 1 <= ${#} )) || { echo "missing mandatory argument" 2>&1 ; exit 1; };

case "$ACTION" in
  (dry|prune)
    :
  ;;
  (*)
    echo "Invalid argument"
    exit 1
  ;;
esac