2015-09-23 51 views
2

我要寫一個bash腳本,它返回一個給定的PDF文件列表中的標題和文檔類型以及一些其他內容。所以我試圖編寫一個函數來獲取文檔類型。當文檔類型爲ACM或MIT時,它可以正常工作,但當輸出處於elif塊時,它顯示「找不到命令」。我的代碼是在這裏 -Bash:elif not working

#!/bin/bash 
function get_type(){ 
if less "$1" | grep -q -i "ACM TRANSACTIONS" 
then 
type="ACM Transactions" 
elif less "$1" | grep -q -i "journal homepage: www.elsevier.com" 
then 
type= "ELSEVIER" 
elif less "$1" | grep -q -i "IEEE TRANSACTIONS" 
then 
type= "IEEE Transactions" 
else 
type="MIT Press" 
fi 
echo $type 
} 
for file in ~/Desktop/1105063/papers/*; 
do 
get_type "$file" 
done 

這裏是輸出 -

[email protected]:~/Desktop/1105063$ ./test.sh 
./test.sh: line 12: IEEE Transactions: command not found 
[...] 
+3

這裏不需要'less':'grep -qi「SEARCH STRING」「$ 1」'就足夠了。 – chepner

+2

請看看:http://www.shellcheck.net/ – Cyrus

回答

5

注意,在shell中,空白常常劃殼的說法。在=標誌周圍的變量分配中不能有空格。使用

type="IEEE Transactions" 

因爲

type= "IEEE Transactions" 

是一次性的分配type與空字符串,然後試圖執行的命令IEEE Transactions(這顯然不存在)。

+0

謝謝!我現在正在踢自己的這個愚蠢的錯誤。 – Shawon0418

+0

@ user3027677 Heh。發生在我們最好的人身上:-) – Jens

1

刪除作業前的空格。

type= "ELSEVIER" 

而且,這是一個很好的做法,把裏面的括號命令:

if (less "$1" | grep -q -i "ACM TRANSACTIONS") 
+3

括號是*恐怖*練習;他們沒有理由就誘發一個子殼。 – chepner

+0

我不知道subhell ...真的嗎? – MtCS

1

一個建議:

#!/bin/bash 

function get_type(){ 
    if grep -q -i "ACM TRANSACTIONS" "$1"; then 
    type="ACM Transactions" 
    elif grep -q -i "journal homepage: www.elsevier.com" "$1"; then 
     type="ELSEVIER" 
     elif grep -q -i "IEEE TRANSACTIONS" "$1"; then 
     type="IEEE Transactions" 
     else 
     type="MIT Press" 
    fi 
    echo "$type" 
} 

for file in ~/Desktop/1105063/papers/*; do 
    get_type "$file" 
done 
+0

謝謝!我會試試這個。 – Shawon0418

+0

我修復了3個錯誤。 – Cyrus

+0

我正在閱讀pdf文件,所以它不會沒有更少的工作。感謝您的幫助,但。 – Shawon0418

0

您可以避免ELIF以一個開關結構。 不是最好的例子case工作,你需要將var轉換爲小寫,並用反斜槓轉義所有空格。

#!/bin/bash 

function gettype { 
    # echo "Debug: Input $1" 
    typeset -l x 
    x=$1 
    # echo "Debug: x=$x" 
    case "$x" in 
     *acm\ transactions*) echo "ACM Transactions" ;; 
     *journal\ homepage:\ www.elsevier.com*) echo "ELSEVIER" ;; 
     *ieee\ transactions*) echo "IEEE Transactions" ;; 
     *) echo "MIT Press" ;; 
    esac 
} 

# Some test-calls 
gettype "String with acm transActions" 
gettype "String without transActions written complete" 
gettype "String with the journal homepage: WWW.ELSEVIER.COM in uppercase." 

編輯: 這gettype()可以從OP的將gettype()不同。
我的gettype()解析一個字符串,OP將搜索文件名爲$ 1的文件。
當你想使用我的gettype(),你首先必須從pdf中提取正確的字符串(也許像https://stackoverflow.com/a/32466580/3220113)。

+0

是的!你應該這樣做!更好:D bash語言是非常強大的。你可能可以用128種不同的方式做同樣的事情。 – MtCS