如何使用cp src/* des/复制非目录文件且抑制目录警告?
Great question! That annoying warning pops up because cp src/* des/ tries to copy everything matching the glob, including directories, and cp won't copy directories without the -r flag. Here are a few clean ways to copy only non-directory files without those warnings:
方法1:使用find命令(通用跨shell)
find lets you explicitly filter for regular files, so it avoids trying to copy directories entirely:
find src -maxdepth 1 -type f -exec cp {} des/ \;
-maxdepth 1ensures we only look at files directly insrc/(not subdirectories inside it)-type ftargets only regular files (skips directories, symlinks, etc.)-exec cp {} des/ \;runscpon each matching file
方法2:Shell循环判断(直观易读)
You can loop through every item in src/ and only copy it if it's a regular file:
for file in src/*; do if [ -f "$file" ]; then cp "$file" des/ fi done
This checks each path with -f (test if it's a regular file) before running cp, so directories are skipped silently without triggering warnings.
方法3:使用rsync(功能强大,适合复杂场景)
If you have rsync available (it's preinstalled on most systems), it's a great alternative that handles this case cleanly:
rsync -av --exclude='*/' src/ des/
-aenables archive mode (preserves permissions, timestamps, etc.)-vadds verbose output (optional, remove it if you don't want feedback)--exclude='*/'tellsrsyncto skip all directories, so only files get copied
方法4:屏蔽特定警告(快速但不够精准)
If you just want to suppress that specific warning (not all errors), you can redirect the stderr output for only that message. Note this is less precise than the above methods, but works for quick one-liners:
cp src/* des/ 2>&1 | grep -v "is a directory (not copied)" >/dev/null
This pipes stderr to grep to filter out the unwanted warning, while still letting actual errors (like permission issues) show up.
内容的提问来源于stack exchange,提问作者Nisba

