1

I would like to put below check in a for loop but do not know how to put the variables as input list, just like $A,$B,$C

A="file name1.txt"
B="file name2.txt"
C="file name3.txt"

if [[ ! -f "$A" ]]; then
    echo "file $A not exist"
fi

if [[ ! -f "$B" ]]; then
    echo "file $B not exist"
fi

if [[ ! -f "$C" ]]; then
    echo "file $C not exist"
fi
6
  • 1
    Try for f in file1 file2 file3; do if [[ ! -f $f ]]; then echo "file $f not exist"; fi; done Commented Sep 15, 2022 at 15:38
  • 2
    I'd start by using an array instead of a bunch of different variables. Commented Sep 15, 2022 at 15:45
  • I'd use -e instead. Commented Sep 15, 2022 at 15:46
  • You definitely can write for file in "$A" "$B" "$C"; do if [[ ! -f "$file" ]]; then ..., but why would you make that extra work for yourself instead of using an array? Commented Sep 15, 2022 at 15:50
  • Good suggestion, I missed the quote so it not work for me! let me try your code! Commented Sep 15, 2022 at 16:08

2 Answers 2

2
#!/bin/bash
A="file name1.txt"
B="file name2.txt"
C="file name3.txt"
for file in "$A" "$B" "$C"; do
    if [[ ! -f "$file" ]]; then
        echo "file $file not exist"
    fi
done

The use of [[ is not POSIX and supported only on ksh, zsh, and bash. It does not require a fork() and is, in general, safer. You can substitute [ and ] respectively for a POSIX compliant script.

Sign up to request clarification or add additional context in comments.

Comments

2

you can use the following commands:

#!/bin/bash

FILES_TO_CHECK_ARRAY=( "file name1.txt" "file name2.txt" "file name3.txt"  )

for current_file in "${FILES_TO_CHECK_ARRAY[@]}"
do

  if [[ ! -f "${current_file}" ]]; then
    echo "file ${current_file} not exist"
  fi

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.