Re: [問題] 判斷文字檔是否出現 "i=0" 字串

看板Linux作者 (mself)時間14年前 (2011/08/17 21:58), 編輯推噓2(207)
留言9則, 3人參與, 最新討論串2/2 (看更多)
※ 引述《mself (mself)》之銘言: : dear 各位 : : 我想寫 bash shell 判斷文字檔是否包含 "i=0" 這個字串 : 我用 result=`grep "i=0" text.txt` : 再判斷 if [$result==""] : : 因為$result裡包含 "=" : 我這樣寫會有問題 : : 請問怎麼做比較對呢? : 謝謝 : : -- : ※ 發信站: 批踢踢實業坊(ptt.cc) : ◆ From: 203.73.9.202 : → HamalAri:我用 $result == "" 沒有問題啊?? 08/16 23:39 : 推 guessi: grep -q "i=0" input && RET=0 || RET=1 ; 08/16 23:41 : → guessi: if test RET = 0 ; then ...; else ...; fi 08/16 23:41 : → guessi: echo $SHELL; 確認一下你是否在使用bash 你原本的應該也ok 08/16 23:44 : → firejox:if [ "$result" == "" ] ? 08/16 23:48 test 文字檔裡寫了一行: i=0 要執行的 script #!/bin/bash echo $SHELL echo '--------' grep -q "i=0" test && echo 'i=0 found' grep -q "i=0" test || echo 'i=0 not found' grep -q "k=0" test && echo 'k=0 found' grep -q "k=0" test || echo 'k=0 not found' echo '---------' result=`grep "i=0" test` echo $result if [$result!=""];then echo 'i=0 found' else echo 'i=0 not found' fi 執行結果: /bin/bash -------- i=0 found k=0 not found --------- i=0 ./testgrep: line 15: [i=0!=]: command not found i=0 not found guessi 版友建議的 grep -q 的方法 work 但直接用 if 判斷 grep 出來的字串,好像字串會被展開成指令 就會有錯 用"" 把變數刮起來也是有一樣的錯誤 不曉得什麼情況變數會被展開成指令?什麼情況不會呢 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 203.67.8.76

08/17 22:07, , 1F
if [ "$result" != "" ]; then ....
08/17 22:07, 1F

08/17 22:07, , 2F
if ["$result"!=""];then .... not this
08/17 22:07, 2F

08/17 22:08, , 3F
mind the "space" before ']' and after '['
08/17 22:08, 3F

08/17 22:09, , 4F
input " i = 0 someword " in ur text file,
08/17 22:09, 4F

08/17 22:10, , 5F
then echo $result :)
08/17 22:10, 5F

08/17 23:01, , 6F
謝謝~確實是中刮號前後空白的關係~
08/17 23:01, 6F

08/18 01:26, , 7F
[是個執行檔 和test差不多 不過[的最後面一定要接著]
08/18 01:26, 7F

08/18 01:27, , 8F
所以要用空白隔開 要不然他會認為你要執行["$result"!=""]
08/18 01:27, 8F

08/18 08:01, , 9F
謝謝 ckclark 講解其中的原理~
08/18 08:01, 9F
文章代碼(AID): #1EIyZqr5 (Linux)
文章代碼(AID): #1EIyZqr5 (Linux)