2015-08-08 41 views
-2

我想制作一个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 
+0

在那里,需要通过其他方式来做到这一点伊斯利我想.. – Vanture

+0

因为我不是在Bash中那么好,但只需要有这样下去我的私人项目。 – Vanture

回答

0

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

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 
+0

如果我使用这个代码 “#/斌/庆典 最新= $(LS -tl | sed的-n 2P)! CP -r test.txt的$最新的” 它不工作是说: “CP:无效选项 - 'W' 尝试'CP --help”以获取更多信息 。” – Vanture

+0

究竟做'LS -tl | sed -n 2p'输出? – rojomoke

+0

如果我只执行该命令(不是在Bash脚本中),它将显示最新制作的目录输出:“drwxr-xr-x。2 root root 4096 Aug 8 09:53 test-2 ” 但是,if我做了它的Bash脚本,它没有,工作.. – Vanture

相关问题