- Linux shell script : make a folder with the current date name
- Linux shell script : make a folder with the current date name
- Powershell File Rename Date/Time
- How to create a folder using a name based on the current date in Powershell?
- Linux/ make folder with date name
- ⏱️ Как создать каталоги или файлы с именами на текущую дату/время/месяц/год на Linux
- Создание каталогов или файлов с именами текущей даты / времени / месяца / года на Linux
- Создание каталогов или файлов с произвольным именем с текущей датой
- Создание каталогов файлов в формате ISO
- Больше примеров
- shell script to create folder daily with time-stamp and push time-stamp generated logs
- 2 Answers 2
Linux shell script : make a folder with the current date name
Use following date format It should works on most file systems but it could be too long for MS DOS FAT. Question: I am trying to make a simple backup script and i have problem creating a folder with the curent date for name My script is that and basically the problem is on the last line Ouput: The path is triply checked that is existing until /media/0362-BA96/ SOLVED : Did what janisz said the final script looks like Solution 1: Trying changing it to: Solution 2: is not valid on FAT (it is used to specify disk).
Linux shell script : make a folder with the current date name
I am trying to make a simple backup script and i have problem creating a folder with the curent date for name
My script is that and basically the problem is on the last line
drivers=$(ls /media/) declare -i c=0 for word in $drivers do echo "($c)$word" c=c+1 done read -n 1 drive echo c=0 for word in $drivers do if [ $c -eq $drive ] then backuppath="/media/$word/backup" fi c=c+1 done echo "doing back up to $backuppath" cp -r /home/stefanos/Programming $backuppath/$(date +%Y-%m-%d-%T)
(0)0362-BA96 (1)Data (2)Windows 0 doing back up to /media/0362-BA96/backup cp: cannot create directory `/media/0362-BA96/backup/2012-12-05-21:58:37': Invalid argument
The path is triply checked that is existing until /media/0362-BA96/
SOLVED : Did what janisz said the final script looks like
drivers=$(ls /media/) declare -i c=0 for word in $drivers do echo "($c)$word" c=c+1 done read -n 1 drive echo c=0 for word in $drivers do if [ $c -eq $drive ] then backuppath="/media/$word/backup" fi c=c+1 done echo "doing back up to $backuppath" backup()< time_stamp=$(date +%Y_%m_%d_%H_%M_%S) mkdir -p "$/$$1" cp -r "$" "$/$$1" echo "backup complete in $1" > #####################The paths to backup#################### backup "/home/stefanos/Programming" backup "/home/stefanos/Android/Projects" backup "/home/stefanos/Dropbox"
time_stamp=$(date +%Y-%m-%d-%T) mkdir -p "$/$" cp -r /home/stefanos/Programming "$/$"
: is not valid on FAT (it is used to specify disk). Some of M$ invalid character works on GNU/Linux systems but it is safer to avoid them (just replace with . ). Use following date format
It should works on most file systems but it could be too long for MS DOS FAT. More info you will find here.
Create folder with current date as name in powershell, The folder name should be «yyyy-MM-dd» (acording to the .NET custom format strings). I know that to create folder I need to use this command: New-Item -ItemType directory -Path «some path» A possible solution could be (if I want to create the folder in the same directory as the script is: Usage exampleNew-Item -ItemType Directory -Path «.\$((Get-Date).ToShortDateString())»Feedback
Powershell File Rename Date/Time
I have what should be a simple problem, but I just can’t seem to get it right. I have a file that has two file extensions. We retrieve the file, decrypt it and save the encrypted file to a backup folder with a date/time stamp showing when the file was processed. All I want to do is to have the date/time stamp put before the two extensions instead of between them. There has to be a simple one line answer to this, but I can’t find it. Any suggestions?
Original File Name — DAILY AP FILES.ZIP.pgp
Current Rename File Name — DAILY_AP_FILES.ZIP-02182013-155123.pgp
Desired Rename File Name — DAILY_AP_FILES-02182013-155123.pgp
Get-ChildItem "$dlpath\*.pgp" | ForEach-Object
Get-ChildItem "$dlpath\*.pgp" | ForEach-Object
Get-ChildItem "$dlpath\*.pgp" | ForEach-Object
Try this modification, improve because sort by date
$source_path="D:\Transferencia" $backup_folder="D:\Transferencia_Backup" Get-ChildItem "$source_path\*.pgp" | ForEach-Object
Linux shell script : make a folder with the current date, @janisz yes its working on tmp creating the date folder etc . Even works if i just right in the terminal cp somefile /media/0362-BA96/backup/ so the usb drive its ok and there is not any problem with it, its just dosent work in the srcipt
How to create a folder using a name based on the current date in Powershell?
I have around 50 xml files that are newly generated everytime I run a particular logic. Now I want these 50 files to be stored inside a particular date-time folder. No matter how many times ever I run that logic for one particular date, the xml files should be overwritten for that particular date only (based on the hhmmss). In simple , How to create a folder using a name based on the current date and store the xml files in them depending on the date?
For Eg: there are 3 xml files file_1.xml, file_2.xml and file_3.xml
Now I want a folder to be created in the format-
that would house all the xml files in them.
For Eg: Xml_20121029_180912
would be the folder created for today’s date. And all the 3 xml files will be stored in this for today.
For tomorrow the folder name would be:
$location = New-Item -Path . -ItemType Directory -Name ("XML_$(Get-Date -f dd_MM_yyyy_hhmmss)") $rptdir = "C:\Test" $ rptdir = ($rptdir + '\' + $location.Name) $outputFile= "$rptdir\File_2.xml" $row = "\\shared\Data\DevSB\CS\appSomeSystem.dll" & /f:$row /o:$outputFile
Output Error : Could not find part of the path «C:\test\XML_29_10_2012_091717\File2.xml.
The issue here is- The folder XML_29_10_2012_091717 is created with File2.xml in it but not inside the C:\Test but where the script is.
I need XML_29_10_2012_091717 to be created in C:\test with File2.xml inside it.
Environment : Win Xp Professional.
Any help would be greatly appreciated.
New-Item -Path . -ItemType Directory -Name ("XML_$(Get-Date -f ddMMyyyy_hhmmss)")
$location = New-Item -Path c:\test -ItemType Directory -Name ("XML_$(Get-Date -f dd_MM_yyyy_hhmmss)") $outputFile= "$($location.fullname)\File_2.xml"
New-Item -Path . -ItemType Directory -Name (Get-Date -f dd_MM_yyyy)
You can also use md or mkdir
$location = New-Item -Path $rptdir -ItemType Directory **-force** -Name ("XML_$(Get-Date -f dd_MM_yyyy_hhmmss)")
How about adding a -force cmd-let here?
Create file with date and time stamp in Powershell, I would like to create a file whose name is the current time. i’ve tried this code below but it’s not working : Powershell — modify Date and Time of a file to reflect its filename. 5. Powershell Current time minus n …
Linux/ make folder with date name
I try to create folder in my server with the current date.
So I wrote the next lines:
$ mkdir # date +”%d-%m-%Y” cd # date +”%d-%m-%Y”
and save it as .sh , But for somme reasom it doesn’t work. What can be the reason?
mkdir "$(date +"%d-%m-%Y")" cd "$(date +"%d-%m-%Y")"
In the extreme case a day passes between the first and the second statement, that won’t work. Change it to:
Explanation: The $(. ) returns the output from the subcommands as a string, which we store in the variable d .
(Quoted the variables as suggested by tripleee)
Powershell File Rename Date/Time, All I want to do is to have the date/time stamp put before the two extensions instead of between them. There has to be a simple one line answer to this, but I can’t find it. Any suggestions? Current Rename File Name — DAILY_AP_FILES.ZIP-02182013-155123.pgp. Desired Rename File Name — …
⏱️ Как создать каталоги или файлы с именами на текущую дату/время/месяц/год на Linux
Вы когда-нибудь хотели создать каталог или файл и назвать его текущей датой / временем / месяцем / годом из командной строки в Linux?
Это будет полезно, если вы хотите что-то сохранить, например, фотографии, в каталогах с указанием даты, когда они действительно были сделаны.
Показанные далее команды создадут каталоги или файлы с именами с текущей датой или временем на основе часов вашего компьютера.
Создание каталогов или файлов с именами текущей даты / времени / месяца / года на Linux
Чтобы создать каталог и назвать его текущей датой, просто запустите:
Эта команда создаст каталог и назовет его сегодняшней датой в формате dd: mm: yyyy.
Аналогично, чтобы создать файл с текущей датой, временем, месяцем, годом, просто замените «mkdir» командой «touch»:
Создание каталогов или файлов с произвольным именем с текущей датой
Как насчет пользовательского имени для каталога или файла с датой / временем / месяцем / годом?
Создание каталогов файлов в формате ISO
Если вы хотите использовать формат даты ISO (например, 2020-06-06), запустите:
Все вышеперечисленные три команды дают одинаковый результат.
Для создания файлов просто замените mkdir командой «touch».
Больше примеров
Если вы хотите только день текущей даты, используйте:
Эта команда создаст каталог только с текущим днем в имени. т.е. 06.
Точно так же вы можете создавать каталоги с именем текущего месяца только в имени:
Обратите внимение что S – заглавная
Чтобы назвать каталог с текущими минутами, используйте заглавную M:
Во всех приведенных выше примерах мы создали каталоги с номерами на их именах.
Что если вы хотите назвать каталоги с фактическим названием текущего дня / месяца, например, Saturday, October и т. д.?
Вот список поддерживаемых операторов, которые вы можете использовать для именования каталогов с указанием текущего дня, месяца, времени, года, дня недели, дня месяца, часового пояса и т. д.
%a locale's abbreviated weekday name (e.g., Sun) %A locale's full weekday name (e.g., Sunday) %b locale's abbreviated month name (e.g., Jan) %B locale's full month name (e.g., January) %c locale's date and time (e.g., Thu Mar 3 23:05:25 2005) %C century; like %Y, except omit last two digits (e.g., 20) %d day of month (e.g., 01) %D date; same as %m/%d/%y %e day of month, space padded; same as %_d %F full date; same as %Y-%m-%d %g last two digits of year of ISO week number (see %G) %G year of ISO week number (see %V); normally useful only with %V %h same as %b %H hour (00..23) %I hour (01..12) %j day of year (001..366) %k hour, space padded ( 0..23); same as %_H %l hour, space padded ( 1..12); same as %_I %m month (01..12) %M minute (00..59) %n a newline %N nanoseconds (000000000..999999999) %p locale's equivalent of either AM or PM; blank if not known %P like %p, but lower case %q quarter of year (1..4) %r locale's 12-hour clock time (e.g., 11:11:04 PM) %R 24-hour hour and minute; same as %H:%M %s seconds since 1970-01-01 00:00:00 UTC %S second (00..60) %t a tab %T time; same as %H:%M:%S %u day of week (1..7); 1 is Monday %U week number of year, with Sunday as first day of week (00..53) %V ISO week number, with Monday as first day of week (01..53) %w day of week (0..6); 0 is Sunday %W week number of year, with Monday as first day of week (00..53) %x locale's date representation (e.g., 12/31/99) %X locale's time representation (e.g., 23:13:48) %y last two digits of year (00..99) %Y year %z +hhmm numeric time zone (e.g., -0400) %:z +hh:mm numeric time zone (e.g., -04:00) %::z +hh:mm:ss numeric time zone (e.g., -04:00:00) %. z numeric time zone with : to necessary precision (e.g., -04, +05:30) %Z alphabetic time zone abbreviation (e.g., EDT)
shell script to create folder daily with time-stamp and push time-stamp generated logs
I would like to create one folder daily with date time-stamp and push log files in to respective date folder when generated. I need to achieve this on AIX server with bash.
What about a cronjob that creates the directory at 00.00 every night? And then modify actual cronjob to push files to this directory.
I would recommend mkdir -p for creating missing directory each time without complaining if it already exists. What if 00:00 job fails to run for some reason (system being down), do we want all daily jobs to fail because of it?
Thanks for the suggestions. I am not going to configure the above requirement in the cronjob. I have a shell script which creates log files. i need to write some script to have the directory and push generated logs in to that
2 Answers 2
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 ''); # 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