Why does my date command in bashrc keep changing the month?

0
0
Asked By CuriousCoder42 On

I'm having a weird issue with an alias in my bashrc file where I'm trying to format a date string. The command I'm using is `$(date +%Y)$(date +%M)KW$(date +%V)-$(( $(date +%V) +2))`. It occasionally evaluates to something like `2024/23/KW49-51`, which is not what I expected. The month seems to change randomly when I source my bashrc. Can someone explain what's going on?

3 Answers

Answered By AdminGeek On

The `man date` command shows that `%M` refers to minutes (00..59). So, when you're debugging, always double-check the man pages for the correct format codes. If your `man date` doesn't help, try looking up `man strftime` for more options.

Answered By BashBuddy99 On

It looks like you're using `$(date +%M)`, but that actually gives you the minutes, not the month! For the month, you want `$(date +%m)`. That's why you're seeing those odd numbers popping up.

DateDissecter -

Thanks for clarifying! I didn’t realize there was such a difference between `%m` and `%M`. This is definitely the answer.

Answered By ShellSeeker85 On

Yeah, you shouldn’t call `date` multiple times for the same values. You can optimize your command by storing the results in variables. For example:

```bash
read y m w <<<$(date +'%Y %m %V')
echo "$y/$m/KW$w-$(( w + 2 ))"
```
This way, you won't run into those problems with the month changing unexpectedly.

HelpfulHans -

Good point! It’s a lot cleaner and avoids potential mistakes with inconsistent outputs.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.