Bash command stopped working after adding inline comment

Viewed 32

The assignment of a new value generated in a subshell does work without the trailing comment:

newname=$(echo "$newname" | sed 's@TD.'"$oldnewTD"'@TD.r'"$ftd1"'@')

But the variable newname stays unchanged if a trailing comment is added:

newname=$(echo "$newname" | sed 's@TD.'"$oldnewTD"'@TD.r'"$ftd1"'@')# let us not change NonEqRead to NonEq

Why?

Bash version 5.0.3.

1 Answers

It turned out the space BEFORE the hash is extremely important in bash — something not frequently mentioned because it apparently seems too obvious due to otherwise impaired readability. When You use the syntax highlighting, however, it is easy to leave out that whitespace without noticing it (editor-dependent problem, of course; e.g., vim is affected). I spent a good time trying to figure out where the error was.

newname=$(echo "$newname" | sed 's@TD.'"$oldnewTD"'@TD.r'"$ftd1"'@') # let us not change NonEqRead to NonEq

Without the whitespace, the whole line silently fails (i.e., without any error message). As far as I understand, bash tries to interpret the hash as a some modifier to the subshell or to the assignment operator. In any case, this seems to be connected with how the bash scripts are read word by word.

See the explanation for a related case: https://stackoverflow.com/a/60238806/2010413

Related