Tag Archives: date

Bash hour date formatting issue

The little things that can trip you up. I had completed a bash script that took some log files, moved & renamed and then archived. Quite a common usage of the Linux shell. Worked yesterday, but this morning I was getting errors. Edited script file below

PREFIX=$(date +"%k%M")
# Edited

for FILE in 2* ; do
  mv $FILE temp/$PREFIX-$FILE;

# and more

Why would the mv work yesterday, but fail this morning, with errors about target not a directory. The answer is in the use of the date formatting %k. From the man page:

%k     hour ( 0..23)

The hour in 8:53 using %k does not return 8, its is 8 with a space in front of it. This only became obvious when I placed double quotes around the mv destination.
Simple fix, use %H, which will return two digits, in this case 08. Problem solved.