0

I am trying to build a list of files I didn't find before running a script. Like a pre-req checking.

CheckPrerequisite() {
matched=1
msg="Couldn't find"

    if ! [[ -f $path/file1 ]]; then
        msg=$msg"\n file1"
        matched=0
    fi

    if ! [[ -f $path/file2 ]]; then
        msg=$msg"\n file2"
        matched=0
    fi

    if ! [[ -f $path/file3 ]]; then
        msg=$msg"\n file3"
        matched=0
    fi

    if [[ matched -ne 1 ]]; then
        printf "$msg"
        exit
    else
        printf "***** Pre-requisites are met. *****"
    fi
}

Expected Output

Couldn't find

file1

file2

file3

Actual Output

Couldn't find\n file1\n file2\n file3

Shivam Chauhan
  • 117
  • 1
  • 9
  • See your code running at https://ideone.com/Hc9gPt, printing the expected output rather than the actual output. Can you fork it to provide a reproducer that *really does* cause the problem at hand? – Charles Duffy Mar 13 '20 at 23:35
  • (That said, this isn't particularly good form; consider `printf '%b\n' "$msg"` if you are going to generate your list of missing files this way, but if I were writing this code myself, I would generate an *array* of missing files, not a string with a message about them) – Charles Duffy Mar 13 '20 at 23:36
  • 2
    ...that is to say, `missing_files=(); for file in file1 file2 file3; do [[ -f $path/$file ]] || missing_files+=( "$file" ); done`, and then later, `(( ${#missing_files[@]} )) && { printf '%s\n' 'Couldn't find:'; printf ' %s\n' "${missing_files[@]}"` – Charles Duffy Mar 13 '20 at 23:38
  • ...that way you don't need a separate `matched` variable at all, you just check if the array is empty or not. – Charles Duffy Mar 13 '20 at 23:38

0 Answers0