将文件复制到最新目录

时间:2015-08-08 13:35:13

标签: linux bash scripting

我想制作一个可以看到最新制作的目录的Bash脚本,如果它找到了将文件复制到该目录所需的最新目录。

目前我有这段代码

    #!/bin/bash

        cd /home/test/hello
        echo "Searching, the latest made Directory!"
        ls -tl | sed -n 2p
#It is not copying yet, because i can't figure out how to let it Copy the stuff to the newest Directory

这段代码显示了最新制作的目录,但是我无法弄清楚如何制作它以便它将项目复制到该目录

以此为例。

./script.sh
# Searching the newest Directory
# Found out that the newest Directory is Dir-1
# Copy the files to the Directory Dir-1
-------------------------------------------------------
./script.sh
# Searching the newest Directory
# Found out that the newest Directory is Dir-2
# Copy the files to the Directory\Dir-2
-------------------------------------------------------
./script.sh
# Searching the newest Directory
# Found out that the newest Directory is Dir-3
# Copy the files to the Directory Dir-3

1 个答案:

答案 0 :(得分:0)

您只需打印最新目录的名称,因此您不需要ls的-l选项。这也删除了总数' line,所以你想要的输出是第一行。

ls -t | sed -n 1p

然后使用$()command substitution)语法将命令的输出捕获到变量中:

latest=$(ls -t | sed -n 1p)

然后您可以在cp命令中使用该变量:

cp file file file $latest

这一切都假定您没有比目标目录更新的普通文件,并且您的目录名称中没有空格或其他异常字符。

使用head命令获取ls输出的第一行而不是sed可能会稍快一点。

ls -t | head -1
相关问题