I am configuring a Sublime Text (ST) build system on macOS. I would like to create a build system variant that outputs the build products to a folder in my user library, but
It is indeed possible to introduce custom variables into a build, but it's a somewhat complicated task in that you have to write a Sublime Plugin to do the job.
In particular, there is a key you can include in your sublime-build
file named target
that tells Sublime what internal command it should execute in order to perform the build. When this key is not present (which is most of the time), it defaults to the exec
internal command, which is responsible for most of the build process, including capturing and showing the output in the panel, injecting error phantoms as appropriate, and so on.
By creating your own custom WindowCommand
instance and including a target
in the sublime-build
file, Sublime will execute your command instead of the default, which allows you to interpret variables as you see fit.
An example of such a build system is available here if you'd like to go this route. In a nutshell it is a custom command that expands variables out and then invokes the internal exec
command to actually do the job.
With all of this said, you can use environment variables in commands directly if you want, so if your goal is to come up with a folder in a known location that's based on an environment variable, you can do that with no changes at all.
The catch here is that on MacOS and Linux, the $
character is used by the shell to denote a variable, but Sublime uses $
to denote it's own variables as well. Thus you need to perform a bit of "quoting magic" to get things to work.
If you try to use for example $HOME
to expand to the home directory, it will expand out to be an empty string. This is because when Sublime is getting ready to execute the build it expands all variables; variables whose values it does not know get replaced with an empty string instead. This isn't a supported build variable, so it's considered empty.
The solution then is to "quote" the dollar sign; \$
tells Sublime not to treat it specially; that allows it to pass the $
through to the command that is ultimately running the shell.
However if you try that, you get the dreaded "No Build System" error in the status line and nothing happens. The reason for this is that the sublime-build
file is JSON, and in JSON \$
is an invalid escape sequence; thus the build fails to load and Sublime does nothing.
The solution there is to use \\$
; that gets interpreted by the JSON loader as being a quoted slash, which converts internally to \$
, which makes Sublime convert it into $
and pass it through to the command.
An example of this is the following simple build system that displays your home directory in the build panel:
{
"shell_cmd": "echo \\$HOME/",
}