shell script to create folder daily with time-stamp and push time-stamp generated logs

后端 未结 2 1698
囚心锁ツ
囚心锁ツ 2021-02-06 11:27

I have a cron job which runs every 30 minutes to generate log files with time-stamp like this:

test20130215100531.log, 
test20130215102031.log  
2条回答
  •  醉梦人生
    2021-02-06 11:45

    Maybe you are looking for a script like this:

    #!/bin/bash
    
    shopt -s nullglob  # This line is so that it does not complain when no logfiles are found
    for filename in test*.log; do # Files considered are the ones starting with test and ending in .log
        foldername=$(echo "$filename" | awk '{print (substr($0, 5, 8));}'); # The foldername is characters 5 to 13 from the filename (if they exist)
        mkdir -p "$foldername"  # -p so that we don't get "folder exists" warning
        mv "$filename" "$foldername"
        echo "$filename $foldername" ;
    done
    

    I only tested with your sample, so do a proper testing before using in a directory that contains important stuff.

    Edit in response to comments:

    Change your original script to this:

    foldername=$(date +%Y%m%d)
    mkdir -p  /home/app/logs/"$foldername"
    sh sample.sh > /home/app/logs/"$foldername"/test$(date +%Y%m%d%H%M%S).log
    

    Or if the directory is created somewhere else, just do this:

    sh sample.sh > /home/app/logs/$(date +%Y%m%d)/test$(date +%Y%m%d%H%M%S).log
    

提交回复
热议问题