如何在shell脚本中检查文件是否存在于文件夹中

时间:2017-11-10 12:32:35

标签: bash shell

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
  size_t size;
  char str[];
} string;

int main(void) {
  char str[] = "aaaaaaaa";
  size_t len_str = strlen(str);
  string *p = malloc(sizeof *p + len_str + 1);
  if (!p) {
    return 1;
  }
  p->size = len_str;
  strcpy(p->str, str);
  puts(p->str);
  strncpy(p->str, str, len_str + 1);
  puts(p->str);
  memcpy(p->str, str, len_str + 1);
  puts(p->str);
  free(p);
}

它总是会在条件和显示文件存在的情况下出现&#39;请帮忙

3 个答案:

答案 0 :(得分:1)

制作一个文件来控制文件是否存在,即ifExists.sh

if [ -f $1 ];
then
 echo $1 " is already present"
else
 echo $1 " is not present"
fi

然后,致电:

$ . ifExists.sh your_file

或直接调用你的脚本:

   dir = /home/TEMP; export dir
   file = filename.txt; export file

   if [ -f $dir/$file ];
    then
     echo $dir/$file " is already present"
    else
     echo $dir/$file " is not present"
    fi

答案 1 :(得分:0)

检查文件是否存在:

if [[ -e "$file" ]]

您能否详细解释一下您在做什么以及您的预期结果是什么? /home/TEMP/filename.txt文件的内容是什么?

答案 2 :(得分:0)

尝试使用以下脚本

files=`ls ./` # put your path here like `ls /me/you/him/`
for file in $files
do
  echo "$file"
  if [ "$file" == "test2.sh" ];then #put the file name you want to compare here in place of test2.sh
    echo "$file present"
            #if you want to break the loop once file found just add statement `break` here
  else
    echo "file not present"
fi
done