Home > front end >  for loop with variable as input list
for loop with variable as input list

Time:09-18

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

CodePudding user response:

#!/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.

CodePudding user response:

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
  •  Tags:  
  • bash
  • Related