3

I am trying to execute the following command in a shell script where adir="mydir" and extType=*.txt

cp "$adir/$extType" "$destination"

However I get:

cp: cannot stat ‘mydir/*.txt’: No such file or directory

but there is such directory and if I execute it by hand in command line it works.

Any ideas what's wrong?

7

You should change "$adir/$extType" to "$adir/"$extType otherwise glob expansion won't take place and it looks for a file exactly with the name of *.txt which can not be found and thus it complains about it with:

cp: cannot stat ‘mydir/*.txt’: No such file or directory
| improve this answer | |
2

Ravexina already pointed out well that globbing doesn't work in double or single quotes, and btw that cp syntax is wrong for multiple files / single destination and needs -t flag.

What you could do as alternative is to use bash arrays:

extType=( "$adir"/*.txt )
cp -t "$destination"   "${extType[@]}" 

Alternatively, loop

for i in "$adir"/*.txt ; do cp "$i"  "$destination"; done
| improve this answer | |
  • Thank you I didn't know that – Jocky Doe Oct 7 '18 at 11:14
  • 4
    The cp syntax isn't that wrong: cp a b c d copies a, b, and c to an existing directory d. – PerlDuck Oct 7 '18 at 11:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.