【发布时间】:2018-04-04 02:17:34
【问题描述】:
假设一个 bash 脚本向其传递了四个命令行参数。这些参数中的每一个都表示输入文件的路径和名称(即INF1、INF2、INF3、INF4)。我想评估这四个输入文件中的每一个,如果它存在并且 - 如果指定的文件不存在 - 退出脚本。
#!/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