0

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?

2 Answers 2

2

in a script

#!/bin/bash

for v; do
if [ ! -f "$v" ]; then
    echo "ERROR | File not found: $v"
    exit 1
fi
done
Sign up to request clarification or add additional context in comments.

1 Comment

You can even skip the in "$@" part, because that's the default if you don't have an in clause.
1

You can declare an array and assing the variables and loop through it.

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

and

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.