【问题标题】:Testing presence of multiple files within loop测试循环中是否存在多个文件
【发布时间】:2018-04-04 02:17:34
【问题描述】:

假设一个 bash 脚本向其传递了四个命令行参数。这些参数中的每一个都表示输入文件的路径和名称(即INF1INF2INF3INF4)。我想评估这四个输入文件中的每一个,如果它存在并且 - 如果指定的文件不存在 - 退出脚本。

#!/bin/bash

# Assigning commandline arguments
INF1=$1
INF2=$2
INF3=$3
INF4=$4

# Check if input files exist
if [ ! -f $1 ]; then
    echo -ne " ERROR | File not found: $1\n"
    exit 1
fi
if [ ! -f $2 ]; then
    echo -ne " ERROR | File not found: $2\n"
    exit 1
fi
if [ ! -f $3 ]; then
    echo -ne " ERROR | File not found: $3\n"
    exit 1
fi
if [ ! -f $4 ]; then
    echo -ne " ERROR | File not found: $4\n"
    exit 1
fi

我认为这里有四个单独的 if 语句是不必要的,并且可以使用单个 if 语句来实现相同的功能,并将其包装在一个循环中。如何减少这方面的代码?

【问题讨论】:

    标签: bash if-statement reduction command-line-arguments


    【解决方案1】:

    在脚本中

    #!/bin/bash
    
    for v; do
    if [ ! -f "$v" ]; then
        echo "ERROR | File not found: $v"
        exit 1
    fi
    done
    

    【讨论】:

    • 您甚至可以跳过in "$@" 部分,因为如果您没有in 子句,这是默认设置。
    【解决方案2】:

    您可以声明一个数组并分配变量并循环遍历它。

    ARRAY=()
    ARRAY+=$1
    ARRAY+=$2 ..
    

    for i in "${arrayName[@]}"
    do
       : 
       # do whatever on $i
    done
    

    【讨论】:

      猜你喜欢
      • 2011-02-16
      • 1970-01-01
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-11
      • 2018-02-08
      • 1970-01-01
      相关资源
      最近更新 更多