检查bash中是否存在参数[files]

时间:2014-08-13 06:48:14

标签: bash if-statement exit

这是我脚本的一部分:

#!/bin/bash

USAGE(){
    echo "Usage: ./`basename $0` <File1> <File2>"
}

if [ "$#" -ne "2" ]; then
    USAGE
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "The file \"$1\" does not exist!"
    exit 1
fi

if [ ! -f "$2" ]; then
    echo "The file \"$2\" does not exist!"
    exit 1
fi

我想检查 file1 是否不存在print:

The file "file1" does not exist!

如果 file2 不存在,则打印:

The file "file2" does not exist!

如果两者都不存在,则打印:

The files "file1" and "file2" don't exist!

我该怎么做?

我想知道最合乎逻辑的(STANDARD)方法是什么。

5 个答案:

答案 0 :(得分:3)

当然你可以做到这一点......有很多方法可以获得这个。最简单的可能是:

if [ ! -f "$1" ] && [ ! -f "$2" ]; then
    echo "The files \"$1\" and \"$2\" do not exist!"
    exit 1
else
    if [ ! -f "$1" ]; then
        echo "The file \"$1\" does not exist!"
        exit 1
    fi

    if [ ! -f "$2" ]; then
        echo "The file \"$2\" does not exist!"
        exit 1
    fi
fi

如果您不想两次进行检查,可以使用变量;像这样的东西:

if [ ! -f "$1" ]; then
    NOT1=1
fi
if [ ! -f "$1" ]; then
    NOT2=1
fi
if [ -n "$NOT1" ] && [ -n "$NOT2" ] 
....

答案 1 :(得分:3)

你可以这样做,所以你只需要test一次文件:

status=""
for file; do
    [ -f "$file" ]
    status+=$?
done

case $status in
    11)
        echo "The files \"$1\" and \"$2\" do not exist!"
        exit 1
        ;;
    10)
        echo "The file \"$1\" does not exist!"
        exit 1
        ;;
    01)
        echo "The file \"$2\" does not exist!"
        exit 1
        ;;
esac

答案 2 :(得分:1)

逻辑是

if [ ! -f "$1" ]; then
    if [ ! -f "$2" ]; then
        echo "The files \"$file1\" and \"$file2\" don't exist!"
        exit 1
    else
        echo "The file \"$1\" does not exist!"
        exit 1
    fi
fi

if [ ! -f "$2" ]; then
    echo "The file \"$2\" does not exist!"
    exit 1
fi

可读是

if [ ! -f "$1" -a ! -f "$2" ]; then
    echo "The files \"$file1\" and \"$file2\" don't exist!"
    exit 1
fi

if [ ! -f "$1" ]; then
    echo "The file \"$1\" does not exist!"
    exit 1
fi

if [ ! -f "$2" ]; then
    echo "The file \"$2\" does not exist!"
    exit 1
fi

首选可读。

也没有像克里斯·梅斯所说的那样对存在进行两次测试也是合乎逻辑的。

答案 3 :(得分:1)

简化Bash

#!/bin/bash
if [[ $# -ne 2 ]]; then
    echo "Usage: ${0##*/} <File1> <File2>"
elif [[ ! -f $1 && ! -f $2 ]]; then
    echo "The files \"$1\" and \"$2\" don't exist!"
elif [[ ! -f $1 ]]; then
    echo "The file \"$1\" does not exist!"
elif [[ ! -f $2 ]]; then
    echo "The file \"$2\" does not exist!"
fi

答案 4 :(得分:0)

您可以使用以下附加条件:

if [ ! -f "$1" ] && [ ! -f "$2" ]; then
  echo "Both files does not exist!"
  exit 1
fi

我不确定你是否需要那个。对于第一个和第二个文件,您拥有的两个条件将足够信息。

或者,您可以使用逻辑OR ||仅使用一个条件。我怀疑用户在理解他们对剧本的错误方面不会有问题:

if [ ! -f "$1" ] || [ ! -f "$2" ]; then
  USAGE
  exit 1
fi