mvdan / sh

A shell parser, formatter, and interpreter with bash support; includes shfmt
https://pkg.go.dev/mvdan.cc/sh/v3
BSD 3-Clause "New" or "Revised" License
7.21k stars 339 forks source link

How to disable formatting #933

Closed theetrain closed 1 year ago

theetrain commented 1 year ago

This is mostly a general question on how to disable formatting for a file since I cannot find it in the README. I have a shell file that performs inline MySQL queries, but sh converts backticks to $() that breaks SQL statements. Here's a real example:

#!/bin/bash

if [ -d /srv/dolt ]; then
  dolt table import -c schools ../Schools.csv --continue
  dolt table import -c students ../Students.csv --continue
  dolt sql -q "ALTER TABLE schools ADD primary key(`School Name`);"
else
  echo container not detected 
fi

But sh converts the backticks in the SQL line to the following invalid line:

-dolt sql -q "ALTER TABLE schools ADD primary key(`School Name`);"
+dolt sql -q "ALTER TABLE schools ADD primary key($(School Name));"

I'm not an advanced shell user, but I would hope that backticks inside double-quoted strings would be respected.

I've seen related issues about how there is no feature for disabling a single line or group of lines. See #342, #700.

I use the shell-format VSCode extension. My workaround is to save without formatting, in VSCode it's typically +K,S.

mvdan commented 1 year ago

That's working as intended. Backticks inside double quotes are command substitutions. So evaluating that field is actually calling the program School with the argument Name. You likely want single quotes, which do not perform expansions.

theetrain commented 1 year ago

Thanks for the information. You're right, replacing double quotes with single quotes no longer formats strings; this works for me.

-dolt sql -q "ALTER TABLE schools ADD primary key(`School Name`);"
+dolt sql -q 'ALTER TABLE schools ADD primary key(`School Name`);'