Bash 检查文件是否存在

Bash 检查文件是否存在,bash,file-io,Bash,File Io,我正处于项目的最后阶段,需要创建一个脚本,该脚本将使用不同的输入在给定次数下运行可执行文件。其中一个输入是保存在与可执行文件分开的文件夹中的文件 在做任何事情之前,我想检查文件是否存在。有两种可能的文件输入可以给出,所以我需要比较它们。可能的输入是 执行癌症9 执行启动程序9 其中,cancer和promotors是程序中要使用的数据集,9是脚本循环必须执行的次数 以下是我的想法: #!/bin/bash #Shell script to execute Proj 4 requiremen

我正处于项目的最后阶段,需要创建一个脚本,该脚本将使用不同的输入在给定次数下运行可执行文件。其中一个输入是保存在与可执行文件分开的文件夹中的文件

在做任何事情之前,我想检查文件是否存在。有两种可能的文件输入可以给出,所以我需要比较它们。可能的输入是

  • 执行癌症9
  • 执行启动程序9
其中,
cancer
promotors
是程序中要使用的数据集,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
标志用于检查文件是否存在。那么,为什么要将文件内容输出到终端?

将空格放在以下位置的
=
右侧:

file1= "Data/BC/bc80-train-1"
file2= "Data/Promoters/p80-train-1"
此外,关键字
then
本身应该在一行上,或者如果与
在同一行上,如果
应该有一个
在此之前:

if [ condition ] ; then
...
fi


您的错误消息混合了
./Data/
~/Data/
,但您的
文件1
文件2
在其定义中既没有
也没有
~

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

删除
file1=
file2=

中的=后的空格不要重复,请使用以下函数:

#!/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

那里的任何代码都不应输出文件的内容。我想你没有给我们看其他代码吧?如果将
set-x
粘贴在代码顶部附近,它将在运行命令之前输出每个命令,有点像bash的调试器。我还强烈建议坚持写第一行
#/bin/bash-u
这将在未设置的变量上出错我刚刚开始编写脚本。这确实是我第一次编写一个有点复杂的脚本,并决定分块进行测试。第一步是检查文件是否存在,第二步是让循环运行。当所有这些都完成后,我将把可执行调用放入。@Jason:然后请从您的问题中删除您关于输出到终端的文件的陈述。如果你把它们从问题中抽象出来,它们在这里就毫无意义了!
#!/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