Reputation: 422
I have a bash script that is copying some files, but it doesn't seem to be working properly. A side note is that there are no matching files in the source directory. But the point of the script is to copy files if there are files to copy.
A basic snippet of what I'm trying to do:
source_loc=/u01
target_log=/u02
/usr/bin/cp "$source_loc"/dir/*file* "$target_loc"/dir/
Results in
Usage: cp [-fhipHILPU][-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src target
or: cp [-fhipHILPU] [-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src1 ... srcN directory
If I add set -x to my script, I get this...
+ /usr/bin/cp /u02/dir/
Usage: cp [-fhipHILPU][-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src target
or: cp [-fhipHILPU] [-d|-e] [-r|-R] [-E{force|ignore|warn}] [--] src1 ... srcN directory
+ set +x
The EXTRA peculiar thing about this is that if I re-run the script without changing anything, I get this as my output:
cp: /u01/dir/*file*: No such file or directory
Now I haven't tested this script with matching files in the source (I will be very shortly) but I want to make sure I'm not missing something. I don't care about getting an error, I just want to be sure I get the correct error (i.e. no such file or directory).
Any insight would be appreciated.
Upvotes: 1
Views: 396
Reputation: 43109
You can use find
as suggested by @elliotfrisch:
find "$source_dir/dir" -type f -name "*file*" -maxdepth 1 -exec cp {} "$target_loc/dir" \;
Alternatively, in Bash, you can capture the glob results into an array and invoke cp
when the array is not empty:
shop -s nullglob # glob expands to nothing if there are no matching files
files=("$source_loc/dir/"*file*)
((${#files[@]} > 0)) && cp "${files[@]}" "$target_loc"/dir/
Upvotes: 1