Assume a bash script to which four commandline arguments are passed. Each of these arguments represents a path to, and a name of, an input file (i.e., INF1
, INF2
, INF3
, INF4
). I would like to evaluate for each of these four input files, if it exists and - if a file does not exist as specified - exit the script.
#!/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
I would think that having four individual if-statements here is unnecessary, and that the same functionality can be achieved with a single if-statement, wrapped into a loop. How can I reduce the code in this aspect?
in a script
#!/bin/bash
for v; do
if [ ! -f "$v" ]; then
echo "ERROR | File not found: $v"
exit 1
fi
done