检查文件是否存在

Jas*_*son 3 bash file-io

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

在做任何事情之前,我想检查文件是否存在.可以给出两种可能的文件输入,因此我需要对它们进行比较.可能的输入是

  • execute cancer 9
  • execute promoter 9

where 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
Run Code Online (Sandbox Code Playgroud)

这样做的问题是它打开文件并将它们输出到终端,每个行的结尾 : command not found

我认为-f-e标志用于检查文件是否存在.那么为什么文件内容会输出到终端呢?

cod*_*ict 5

将空格=放在in 的右侧:

file1= "Data/BC/bc80-train-1"
file2= "Data/Promoters/p80-train-1"
Run Code Online (Sandbox Code Playgroud)

关键字也then应该单独放在一行上,或者如果在同一行上if应该有一个;之前的关键字:

if [ condition ] ; then
...
fi
Run Code Online (Sandbox Code Playgroud)

要么

if [ condition ]
then
...
fi
Run Code Online (Sandbox Code Playgroud)