0

I wrote a simple bash alias to create a sort of daily tmp directory to work in:

alias datdir="mkdir $(date +'%m_%d_%Y')___$RANDOM"

When I call it repeatedly on the same day, I get this:

mkdir: cannot create directory ‘02_04_2022___24499’: File exists

However, when I simply run echo $RANDOM on the terminal, I get different numbers.

I'm running Git Bash on Microsoft Windows 10 Business, Version 10.0.19044 Build 19044

$ bash --version
GNU bash, version 4.4.23(1)-release (x86_64-pc-msys)
Copyright (C) 2016 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>

This is free software; you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
FaraBara
  • 115
  • 7
  • 2
    The double quotes quotes mean that both the command substitution and the `RANDOM` variable are expanded at the time the alias is declared, rather than when it is used. Use single quotes: `alias datdir='mkdir $(date +%m_%d_%Y)___$RANDOM'`. Single quotes can't be nested, so the inner pair can be removed, as they aren't neccesary here. – dan Feb 04 '22 at 12:42
  • I would prefer a function here: `datdir () { mkdir "$(date +'%m_%d_%Y')___$RANDOM"; }`. – chepner Feb 04 '22 at 13:22
  • 2
    I would also consider using `mktemp` instead. It's *possible* for `$RANDOM` to produce the same value more than once if you use `datdir` more than once a day. `mktemp` *guarantees* a unique directory name (as it will simply generate a new name if its first attempt already exists). – chepner Feb 04 '22 at 13:25
  • `mktemp` is much safer for this. In some shells, `$RANDOM` can *deterministically* produce the same numbers repeatedly in some situations involving subshells (see [this question](https://stackoverflow.com/questions/63544826/unix-shell-why-are-the-same-random-numbers-repeated)). – Gordon Davisson Feb 04 '22 at 18:03

0 Answers0