简体   繁体   English

每次在Linux上运行Shell脚本时都会创建一个新目录

[英]creating a new directory each time a shell script is run on linux

I'm trying to create a shell script that copies .log files from one directory to a new directory, with a new name each time the script is run. 我正在尝试创建一个Shell脚本,该脚本将.log文件从一个目录复制到新目录,每次运行该脚本时都使用一个新名称。

For example lets say there's File1.log, File2.log, File3.log in /home/usr/logs 例如,假设在/home/usr/logs有File1.log,File2.log,File3.log

and when this script runs, I want them to be copied to a new location /home/usr/savedlogs/Run1 and the next time it runs... /home/usr/savedlog/Run2 and so on... 当该脚本运行时,我希望将它们复制到新位置/home/usr/savedlogs/Run1 ,下一次运行时... /home/usr/savedlog/Run2 ,依此类推...

I'm not sure if this would be used: 我不确定是否会使用:

cp /home/usr/logs/{File1.log,File2.log,File3.log} /home/usr/savedlogs cp /home/usr/logs/{File1.log,File2.log,File3.log} / home / usr / savedlogs

I'm hoping this is possible in a shell script. 我希望这在Shell脚本中是可能的。 Thank you all for your help in advance, greatly appreciated! 谢谢大家的帮助,不胜感激!

Here is a simple script that might suffice your requirement: 这是一个简单的脚本,可能满足您的要求:

#!/bin/bash

# Get the number of Run* directories present
newnum=$(ls -ld /home/usr/savedlogs/Run* 2>/dev/null | wc -l)

mkdir -p /home/usr/savedlogs/Run${newnum}

cp /home/usr/logs/*.log /home/usr/savedlogs/Run${newnum}

This will start from Run0 and proceeds from there 这将从Run0开始并从那里继续

If you do not care about incrementing directory names, you can do this with a simple timestamp: 如果您不关心递增目录名称,则可以使用简单的时间戳记来实现:

DIR=$(date +%Y%m%d%H%M%S)
mkdir $DIR
cp /home/usr/logs/FileXXX.log /home/usr/savedlogs/$DIR/

This will work as long as your copy operation happens less than once a second. 只要您的复制操作少于每秒一次,就可以使用。

You may try with newDir=$(ls -l /home/usr/savedlogs | grep Run | wc -l) for getting the existing number of directories. 您可以尝试使用newDir=$(ls -l /home/usr/savedlogs | grep Run | wc -l)获取现有目录数。

So the whole script will look like this : 因此,整个脚本将如下所示:

    newDir=$(ls -l /home/usr/savedlogs | grep Run | wc -l)
    mkdir -p /home/usr/savedlogs/Run${newDir}
    cp /home/usr/logs/*.log /home/usr/savedlogs/Run${newDir}

First folder will be Run0 , next Run1 and so on... 第一个文件夹会Run0 ,未来Run1等等...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM