-1

So i wrote a script to create a directory named based on the year + month which is like:

mkdir $(date +"%Y%^b")

which would create a directory like:

2021JAN

However, I would like to store the name in a variable. I tried doing:

dirname = $(date +"%Y%^b")
echo $dirname
mkdir $dirname

But nothing it doesn't seemed to be working. Even echoing it gives a

.
.

What seemed to be causing the issue?

Maxxx
  • 3,688
  • 6
  • 28
  • 55

1 Answers1

0

I'm assuming this is bash or something similar. You cannot have a space between the variable name and the assignment operator in bash. You should also surround the subshell it quotation marks, in case there are any spaces in its output (not that there would be in this case). This works fine:

dirname="$(date +%Y%^b)"
echo $dirname
mkdir $dirname
Alexander Guyer
  • 2,063
  • 1
  • 14
  • 20
  • wow that's new, I didn't know about that having a space would be an issue! Thank you. – Maxxx Jan 17 '21 at 02:58
  • @Maxxx Bash is a "language" hacked together from terminal commands and named executables. Even `if`, `[`, and `]` are just executables (you probably have a file `/usr/bin/[`). As such, almost everything you type into a bash script is treated as the name of an executable to run. If you put a space between `dirname` and `=`, it thinks you're trying to run an executable in the `$PATH` with the name `dirname`, rather than create a variable. – Alexander Guyer Jan 17 '21 at 03:01