0
read -r -p "Enter the filenames: " -a arr

for filenames in "${arr[@]}"; do
   if [[ -e "${filenames}" ]]; then
        echo "${filenames} file exists (no override)"
   else
        cp -n ~/Documents/library/normal.py "${filenames}"
   fi
done

Suppose, I've B.py D.py in a folder.

When I run this script in the same folder and write A.py B.py C.py D.py (undefined number of inputs)
Files named A.py C.py are copied successfully.

Whereas for B.py D.py, it shows B.py file exists (no override) and D.py file exists (not override) respectively.

I want to store elements which did worked and which didn't work in separate arrays from main array ${arr[@]}

arr=('A.py' 'B.py' 'C.py' 'D.py')
didworked=('A.py' 'C.py')
notworked=('B.py' 'D.py')

How can i do that? Any suggestions, please.

1 Answer 1

2

Just append the filename to the corresponding arrays at the right points:

#!/bin/bash
files=('A.py' 'B.py' 'C.py' 'D.py')
files_err=()
files_ok=()
for f in "${files[@]}"; do
   if [[ -e "$f" ]]; then
        echo "$f file exists (no override)"
        files_err+=("$f")
   else
        if cp -n ~/Documents/library/normal.py "$f"; then
            files_ok+=("$f")
        else
            # copy failed, cp should have printed an error message
            files_err+=("$f")
        fi
   fi
done

(I wouldn't use filenames as the loop variable in that for, it's only one filename (at a time), not many.)

6
  • On the systems I have, that implement -n for cp, cp -n does not print a diagnostic message if the destination file exists.
    – Kusalananda
    Commented Jul 8, 2022 at 7:58
  • 1
    @Kusalananda, nor does it return with error status, yep. They had the explicit check there to see if the destination file existed already, so that deals with that. The check on cp is mostly for completeness since the copy could fail for other reasons too. Probably not too commonly, and anything that came up would probably prevent all the copies. Like the disk being full or whatever.
    – ilkkachu
    Commented Jul 8, 2022 at 8:03
  • Hmm... GNU cp -n does not return a non-zero exit status if the destination exists, but other implementations do (tested FreeBSD and macOS). So it's still useful.
    – Kusalananda
    Commented Jul 8, 2022 at 8:05
  • 1
    @Kusalananda, ah, ok. I only quickly tested GNU. And it's enough that it doesn't, since it means the explicit check on the destination file is necessary. If we knew cp -n returns non-zero when the destination exists, the -e test could be dropped.
    – ilkkachu
    Commented Jul 8, 2022 at 8:07
  • cp -n is probably not standardized for the simple reason that test -e already exists.
    – Kusalananda
    Commented Jul 8, 2022 at 8:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .