2015年4月9日 星期四

[linux] 將pipe結果當成if條件使用

enter image description here
shell script真的是方便的工具,最近剛學會一點awk,一些過去很難處理的東西,現在都被簡化了.今天遇到的狀況是:想用shell script將另外一支程式包起來,並將程式的output另外存放,並且根據output的內容回饋給使用者一些訊息.

另外存放比較簡單,加個 > 就可以將輸出導到檔案中.另外就是要根據輸出內容做些摘要,其中一個就是判斷有沒有錯誤訊息輸出.因為我sh不是很熟,所以粗淺的想法就是去掃整個log檔,看有沒有ERROR的文字,如果有就去做某某動作這樣
例如我想查下列文檔中有沒有LICENSE的字時
Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0
可以很簡單下cat index.html | grep -c LICENSE這樣就可以知道LICENSE出現過幾次,所以把這段包到 if 中:
if [ "$(cat index.html | grep -c LICENSE )" = "1" ]; then
  echo "equal 1"
這邊要注意的是,因為最後我們要將grep的結果與“1”來做比較,表示pipe結果要當成變項來使用,這時必須用$( )將指令包起來,同時等號兩邊都必須使用 " "包起來,才能正確執行,今天在這個上面卡超久的Orz.
p.s.另外一個卡很久的地方是 [ ]要和裡面的程式碼保留空格…orz


沒有留言:

張貼留言