如何判断Bash中是否存在常规文件?
我用下面的脚本来查看文件是否存在:
#!/bin/bash
FILE=$1     
if [ -f $FILE ]; then
   echo "File $FILE exists."
else
   echo "File $FILE does not exist."
fi
有什么用,如果我只是想检查,如果文件不存在正确的语法?
#!/bin/bash
FILE=$1     
if [ $FILE does not exist ]; then
   echo "File $FILE does not exist."
fi
  测试命令( [这里]有一个“不”)逻辑运算符,它是感叹号(类似于许多其他语言)。  尝试这个: 
if [ ! -f /tmp/foo.txt ]; then
    echo "File not found!"
fi
Bash文件测试
  -b filename - 阻止特殊文件 
  -c filename - 特殊字符文件 
  -d directoryname - 检查目录是否存在 
  -e filename - 检查文件是否存在,无论类型(节点,目录,套接字等) 
  -f filename - 检查常规文件是否存在,而不是目录 
  -G filename - 检查文件是否存在并由有效的组ID标识 
  -G filename set-group-id - 如果文件存在且为set-group-id,则为true 
  -k filename - 粘性位 
  -L filename - 符号链接 
  -O filename - 如果文件存在并且由有效用户标识拥有,则为true 
  -r filename - 检查文件是否可读 
  -S filename - 检查文件是否是套接字 
  -s filename - 检查文件是否为非零大小 
  -u filename - 检查是否设置了文件set-user-id位 
  -w filename - 检查文件是否可写 
  -x filename - 检查文件是否可执行 
如何使用:
#!/bin/bash
file=./file
if [ -e "$file" ]; then
    echo "File exists"
else 
    echo "File does not exist"
fi 
  测试表达式可以通过使用!  操作者 
#!/bin/bash
file=./file
if [ ! -e "$file" ]; then
    echo "File does not exist"
else 
    echo "File exists"
fi 
你可以用“!”否定表达式:
#!/bin/bash
FILE=$1
if [ ! -f "$FILE" ]
then
    echo "File $FILE does not exist"
fi
  相关的手册页是man test或者等同于man [ - 或help test或help [用于内置的bash命令。 
上一篇: How do I tell if a regular file does not exist in Bash?
下一篇: In Java, difference between package private, public, protected, and private
