I'm trying to write a script that sorts some files, and I got it working manually in the shell (Debian, seems to be dash), but when I run the same code as a script I get "Bad substitution" from line 2 and 3;
#!/bin/bash
LAST_MONTH="${date +'%Y%m' -d 'last month'}"
LAST_MONTH_HYPHEN="${date +'%Y-%m' -d 'last month'}"
Everything I found on SO seemed to be related to different shells, so I've tried #!/bin/shas well as #!/bin/bash. I've also tried running the script as ./filesorter.sh, bash filesorter.sh and sh filesorter.sh, and every permutation gives me some variation on the same "bad substitution" theme
filesorter.sh: line 2: ${date +'%Y%m' -d 'last month'}: bad substitution
filesorter.sh: line 3: ${date +'%Y-%m' -d 'last month'}: bad substitution
Change the curly braces to parentheses.
LAST_MONTH="$(date +'%Y%m' -d 'last month')"
LAST_MONTH_HYPHEN="$(date +'%Y-%m' -d 'last month')"
Curly braces are for variable substitution, as in ${var}, equivalent to $var. Parentheses are for command substitution, as in $(command arg1 arg2).
Shellcheck is a great tool for checking the syntax of shell scripts. When fed your script it says:
SC2154:
dateis referenced but not assigned (for output from commands, use"$(date ...)").
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With