Bad Substitution Error from Variables
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:
date
is referenced but not assigned (for output from commands, use"$(date ...)"
).
Related videos on Youtube
Stuggi
By day: Systems architect specializing on networks and server infrastructure in the energy sector. By night: Playing around with new tech, systems, setups and other necessities of life. Interests: Computer systems, networks, photography, coffee
Updated on June 04, 2022Comments
-
Stuggi almost 2 years
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/sh
as well as#!/bin/bash
. I've also tried running the script as./filesorter.sh
,bash filesorter.sh
andsh filesorter.sh
, and every permutation gives me some variation on the same "bad substitution" themefilesorter.sh: line 2: ${date +'%Y%m' -d 'last month'}: bad substitution filesorter.sh: line 3: ${date +'%Y-%m' -d 'last month'}: bad substitution