2011-11-09 35 views
3

我正處於項目的最後階段,需要創建一個腳本,該腳本可以使用不同的輸入運行可執行文件給定的次數。其中一個輸入是與可執行文件保存在單獨文件夾中的文件。檢查文件是否存在

在做任何事之前,我想檢查文件是否存在。有兩種可能的文件輸入可以給出,所以我需要比較它們。可能的輸入是

  • execute cancer 9
  • execute promoter 9

其中cancerpromoters是在程序中使用的數據集和9是倍腳本回路具有以執行數量。

這是我想出來的:

#!/bin/bash 

#Shell script to execute Proj 4 requirements while leaving the folder 
#structure alone separated. 

file1= "Data/BC/bc80-train-1" 
file2= "Data/Promoters/p80-train-1" 

if [ "$1" == "cancer" ] then #execute command on the cancer dataset 
    echo "Executing on the cancer dataset" 
    if [ -f "$file1" ] then 
     echo "$file1 file exists..." 

    else 
     echo "$file1 file Missing, cancelling execution" 
     echo "Dataset must be in ../Data/BC/ and file must be bc80-train-1" 
    fi 

elif [ "$1" == "promoter" ] then #execute on the promoter dataset 
    echo "Executing on the promoter dataset" 

    if [ -f "$file2"] then 
     echo "$file2 file exists..." 

    else 
     echo "$file2 file missing, cancelling execution" 
     echo "Dataset must be in ~/Data/Promoters/ and file must be p80-train-1" 
    fi 
fi 

的問題,這是它打開文件,並將其輸出到終端,每一行中: command not found

我認爲-f結束-e標誌用於檢查文件是否存在。那爲什麼文件內容輸出到終端?

+0

沒有任何代碼應該輸出文件的內容。我假設你還沒有向我們展示其他一些代碼?如果你在代碼的頂部附近貼上'set -x',它會在運行它之前輸出每個命令,就像bash的調試器一樣。我還*高度*推薦使用第一行'#!/ bin/bash -u',這會在未設置變量時出錯 – Sodved

+0

我剛剛開始將腳本放在一起。這實際上是我第一次將一個有點複雜的腳本放在一起,並決定分塊測試它。第一步是檢查文件是否存在,第二步是讓循環運行。完成所有工作後,我會將可執行調用放入。 – Jason

+0

@Jason:然後,請刪除您的問題中有關正在輸出到終端的文件的聲明。如果你已經從問題中抽象出來,他們在這裏沒有意義! –

回答

5

下降的空間的=在右:

file1= "Data/BC/bc80-train-1" 
file2= "Data/Promoters/p80-train-1" 

而且關鍵字then應該是一條線本身或如果在同一行if應該收到一份;

if [ condition ] ; then 
... 
fi 

OR

if [ condition ] 
then 
... 
fi 
1

你的錯誤信息混合../Data/~/Data/,但你的file1file2不必無論是在他們的定義..~

file1= "Data/BC/bc80-train-1" 
file2= "Data/Promoters/p80-train-1" 
1

file1=刪除=後面的空格和file2=

1

不要重複自己,使用功能:

#!/bin/bash 

checkfile() { 
    echo "Executing on the $1 dataset" 
    file="$2/$3" 
    if [ -f "$file" ] then 
     echo "$file file exists..." 

    else 
     echo "$file file Missing, cancelling execution" 
     echo "Dataset must be in $2 and file must be $3" 
    fi 
} 

case $1 in 
cancer) 
    checkfile $1 Data/BC bc80-train-1 
    ;; 
promoter) 
    checkfile $1 Data/Promoters p80-train-1 
    ;; 
*) 
    echo "Error: unknown dataset. Use 'cancer' or 'promoter'" 
    ;; 
esac