linux - 在 Shell 中,如何将目录的内容移动到同一级别的另一个目录

标签 linux shell

/tmp/test$ ls
dir1  dir2  dirM
/tmp/test$ mv * dirM/
mv: cannot move `dirM' to a subdirectory of itself, `dirM/dirM'

有没有办法使用 shell 脚本将所有内容(dirM 除外)移动到 dirM?

最佳答案

您没有说明您使用的是什么 shell。在符合 POSIX 的 sh 中,您可以遍历目录的内容,跳过 dirM:

for d in ./*/; do
    [ ! -d "$d" ] || [ "$d" -eq "./dirM/" ] && continue
    mv "$d" dirM
done

bash 中,您可以使用扩展模式来匹配除 dirM 之外的所有内容:

shopt -s extglob nullglob
for d in !(dirM)/; do
    mv "$d" dirM
done

无论哪种情况,如果您只是想隐藏错误,请使用

mv * dirM 2> /dev/null

不推荐这样做,因为它会丢弃任何可能发生的错误。

关于linux - 在 Shell 中,如何将目录的内容移动到同一级别的另一个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33487010/

相关文章:

linux - 如何对文件进行 gzip 压缩

Delphi shell 上下文菜单,如何绘制图标

linux - 比较两个不同文件的内容

android - 在构建 cordova 项目时出现 ANDROID_HOME PATH 错误

c - 'wait' 系统调用上的 EINTR

c# - 如何编译单声道源代码

c++ - 如何减少在 linux 中访问新页面时的延迟

php - 禁用 wp-cron,并在多站点环境中运行 linux cron

sqlite - 如何使用elisp创建一个sqlite特定的shell?

shell - 在 dockerfile 中插入条件 RUN 语句