如果不做某事,则使用 IF 查看目录是否存在

using IF to see a directory exists if not do something

如果 $DIR2 的目录名称不同,我正在尝试将目录从 $DIR1 移动到 $DIR2

if [[ ! $(ls -d /$DIR2/* | grep test) ]] 是我目前拥有的。 then mv $DIR1/test* /$DIR2 fi

首先给出

ls: cannot access //data/lims/PROCESSING/*: No such file or directory

当 $DIR2 为空时

但是,它仍然有效。

其次 当我 运行 两次 shell 脚本时。 它不允许我移动具有相似名称的目录。

例如 在 $DIR1 我有 test-1 test-2 test-3 当它 运行s 第一次所有三个目录移动到 $DIR2 之后我在 $DIR1 和 运行 再次执行 mkdir test-4 脚本.. 它不允许我移动 test-4,因为我的循环认为 test-4 已经存在,因为我正在抓取所有 test

我怎样才能绕过并移动 test-4 ?

首先,您可以使用 bash 内置的 'True if directory exists' 表达式检查目录是否存在:

test="/some/path/maybe"
if [ -d "$test" ]; then
    echo "$test is a directory"
fi

但是,您想测试某物是否不是目录。您已经在代码中表明您已经知道如何取反表达式:

test="/some/path/maybe"
if [ ! -d "$test" ]; then
    echo "$test is NOT a directory"
fi

您似乎也在使用 ls 获取文件列表。如果文件不是目录,也许您想遍历它们并执行某些操作?

dir="/some/path/maybe"
for test in $(ls $dir);
do
    if [ ! -d $test ]; then
        echo "$test is NOT a directory."
    fi
done

Machtelt Garrels 的指南是寻找 bash 此类内容的好地方。 His page on the various expressions you can use in if statements 帮了我很多。

如果目标中不存在目录,则将目录从源移动到目标:

为了便于阅读,我将把您的 DIR1DIR2 称为 srcdest。首先,让我们声明它们:

src="/place/dir1/"
dest="/place/dir2/"

注意结尾的斜杠。我们会将文件夹的名称附加到这些路径,以便尾部斜杠使它更简单。您似乎还通过名称中是否包含单词 test 来限制要移动的目录:

filter="test"

所以,让我们首先遍历 source 中通过 filter 的目录;如果它们在 dest 中不存在,让我们将它们移到那里:

for dir in $(ls -d $src | grep $filter); do
    if [ ! -d "$dest$dir" ]; then
        mv "$src$dir" "$dest"
    fi
done

希望能解决您的问题。但请注意,@gniourf_gniourf 在评论中发布了一个 link 应该引起注意!

如果你需要根据某种模式将一些目录移动到另一个目录,那么你可以使用 find:

find . -type d -name "test*" -exec mv -t /tmp/target {} +

Details:

-type d - will search only for directories

-name "" - set search pattern

-exec - do something with find results

-t, --target-directory=DIRECTORY move all SOURCE arguments into DIRECTORY

有很多 exec 或 xargs 用法的例子。

如果你不想覆盖文件,可以在 mv 命令中添加 -n 选项:

find . -type d -name "test*" -exec mv -n -t /tmp/target {} +

-n, --no-clobber do not overwrite an existing file