Functions
just provides many built-in functions for use in expressions, including
recipe body {{…}} substitutions, assignments, and default parameter values.
All functions ending in _directory can be abbreviated to _dir. So
home_directory() can also be written as home_dir(). In addition,
invocation_directory_native() can be abbreviated to
invocation_dir_native().
System Information
arch()— Instruction set architecture. Possible values are:"aarch64","arm","asmjs","hexagon","mips","msp430","powerpc","powerpc64","s390x","sparc","wasm32","x86","x86_64", and"xcore".num_cpus()1.15.0 - Number of logical CPUs.os()— Operating system. Possible values are:"android","bitrig","dragonfly","emscripten","freebsd","haiku","ios","linux","macos","netbsd","openbsd","solaris", and"windows".os_family()— Operating system family; possible values are:"unix"and"windows".
For example:
system-info:
@echo "This is an {{arch()}} machine".
$ just system-info
This is an x86_64 machine
The os_family() function can be used to create cross-platform justfiles
that work on various operating systems. For an example, see
cross-platform.just
file.
External Commands
-
shell(command, args...)1.27.0 returns the standard output of shell scriptcommandwith zero or more positional argumentsargs. The shell used to interpretcommandis the same shell that is used to evaluate recipe lines, and can be changed withset shell := […].commandis passed as the first argument, so if the command is'echo $@', the full command line, with the default shell commandsh -cuandargs'foo'and'bar'will be:'sh' '-cu' 'echo $@' 'echo $@' 'foo' 'bar'This is so that
$@works as expected, and$1refers to the first argument.$@does not include the first positional argument, which is expected to be the name of the program being run.
# arguments can be variables or expressions
file := '/sys/class/power_supply/BAT0/status'
bat0stat := shell('cat $1', file)
# commands can be variables or expressions
command := 'wc -l'
output := shell(command + ' "$1"', 'main.c')
# arguments referenced by the shell command must be used
empty := shell('echo', 'foo')
full := shell('echo $1', 'foo')
error := shell('echo $1')
# Using python as the shell. Since `python -c` sets `sys.argv[0]` to `'-c'`,
# the first "real" positional argument will be `sys.argv[2]`.
set shell := ["python3", "-c"]
olleh := shell('import sys; print(sys.argv[2][::-1])', 'hello')
Environment Variables
env(key)1.15.0 — Retrieves the environment variable with namekey, aborting if it is not present.
home_dir := env('HOME')
test:
echo "{{home_dir}}"
$ just
/home/user1
env(key, default)1.15.0 — Retrieves the environment variable with namekey, returningdefaultif it is not present.env_var(key)— Deprecated alias forenv(key).env_var_or_default(key, default)— Deprecated alias forenv(key, default).
A default can be substituted for an empty environment variable value with the
|| operator, currently unstable:
set unstable
foo := env('FOO') || 'DEFAULT_VALUE'
Executables
-
require(name)1.39.0 — Search directories in thePATHenvironment variable for the executablenameand return its full path, or halt with an error if no executable withnameexists.bash := require("bash") @test: echo "bash: '{{bash}}'"$ just bash: '/bin/bash' -
which(name)1.39.0 — Search directories in thePATHenvironment variable for the executablenameand return its full path, or the empty string if no executable withnameexists. Currently unstable.set unstable bosh := which("bosh") @test: echo "bosh: '{{bosh}}'"$ just bosh: ''
Invocation Information
is_dependency()- Returns the stringtrueif the current recipe is being run as a dependency of another recipe, rather than being run directly, otherwise returns the stringfalse.
Invocation Directory
invocation_directory()- Retrieves the absolute path to the current directory whenjustwas invoked, beforejustchanged it (chdir’d) prior to executing commands. On Windows,invocation_directory()usescygpathto convert the invocation directory to a Cygwin-compatible/-separated path. Useinvocation_directory_native()to return the verbatim invocation directory on all platforms.
For example, to call rustfmt on files just under the “current directory”
(from the user/invoker’s perspective), use the following rule:
rustfmt:
find {{invocation_directory()}} -name \*.rs -exec rustfmt {} \;
Alternatively, if your command needs to be run from the current directory, you could use (e.g.):
build:
cd {{invocation_directory()}}; ./some_script_that_needs_to_be_run_from_here
invocation_directory_native()- Retrieves the absolute path to the current directory whenjustwas invoked, beforejustchanged it (chdir’d) prior to executing commands.
Justfile and Justfile Directory
-
justfile()- Retrieves the path of the currentjustfile. -
justfile_directory()- Retrieves the path of the parent directory of the currentjustfile.
For example, to run a command relative to the location of the current
justfile:
script:
{{justfile_directory()}}/scripts/some_script
Source and Source Directory
-
source_file()1.27.0 - Retrieves the path of the current source file. -
source_directory()1.27.0 - Retrieves the path of the parent directory of the current source file.
source_file() and source_directory() behave the same as justfile() and
justfile_directory() in the root justfile, but will return the path and
directory, respectively, of the current import or mod source file when
called from within an import or submodule.
Just Executable
just_executable()- Absolute path to thejustexecutable.
For example:
executable:
@echo The executable is at: {{just_executable()}}
$ just
The executable is at: /bin/just
Just Process ID
just_pid()- Process ID of thejustexecutable.
For example:
pid:
@echo The process ID is: {{ just_pid() }}
$ just
The process ID is: 420
String Manipulation
append(suffix, s)1.27.0 Appendsuffixto whitespace-separated strings ins.append('/src', 'foo bar baz')→'foo/src bar/src baz/src'prepend(prefix, s)1.27.0 Prependprefixto whitespace-separated strings ins.prepend('src/', 'foo bar baz')→'src/foo src/bar src/baz'encode_uri_component(s)1.27.0 - Percent-encode characters insexcept[A-Za-z0-9_.!~*'()-], matching the behavior of the JavaScriptencodeURIComponentfunction.quote(s)- Replace all single quotes with'\''and prepend and append single quotes tos. This is sufficient to escape special characters for many shells, including most Bourne shell descendants.replace(s, from, to)- Replace all occurrences offrominstoto.replace_regex(s, regex, replacement)- Replace all occurrences ofregexinstoreplacement. Regular expressions are provided by the Rustregexcrate. See the syntax documentation for usage examples. Capture groups are supported. Thereplacementstring uses Replacement string syntax.trim(s)- Remove leading and trailing whitespace froms.trim_end(s)- Remove trailing whitespace froms.trim_end_match(s, substring)- Remove suffix ofsmatchingsubstring.trim_end_matches(s, substring)- Repeatedly remove suffixes ofsmatchingsubstring.trim_start(s)- Remove leading whitespace froms.trim_start_match(s, substring)- Remove prefix ofsmatchingsubstring.trim_start_matches(s, substring)- Repeatedly remove prefixes ofsmatchingsubstring.
Case Conversion
capitalize(s)1.7.0 - Convert first character ofsto uppercase and the rest to lowercase.kebabcase(s)1.7.0 - Convertstokebab-case.lowercamelcase(s)1.7.0 - ConvertstolowerCamelCase.lowercase(s)- Convertsto lowercase.shoutykebabcase(s)1.7.0 - ConvertstoSHOUTY-KEBAB-CASE.shoutysnakecase(s)1.7.0 - ConvertstoSHOUTY_SNAKE_CASE.snakecase(s)1.7.0 - Convertstosnake_case.titlecase(s)1.7.0 - ConvertstoTitle Case.uppercamelcase(s)1.7.0 - ConvertstoUpperCamelCase.uppercase(s)- Convertsto uppercase.
Path Manipulation
Fallible
absolute_path(path)- Absolute path to relativepathin the working directory.absolute_path("./bar.txt")in directory/foois/foo/bar.txt.canonicalize(path)1.24.0 - Canonicalizepathby resolving symlinks and removing.,.., and extra/s where possible.extension(path)- Extension ofpath.extension("/foo/bar.txt")istxt.file_name(path)- File name ofpathwith any leading directory components removed.file_name("/foo/bar.txt")isbar.txt.file_stem(path)- File name ofpathwithout extension.file_stem("/foo/bar.txt")isbar.parent_directory(path)- Parent directory ofpath.parent_directory("/foo/bar.txt")is/foo.without_extension(path)-pathwithout extension.without_extension("/foo/bar.txt")is/foo/bar.
These functions can fail, for example if a path does not have an extension, which will halt execution.
Infallible
clean(path)- Simplifypathby removing extra path separators, intermediate.components, and..where possible.clean("foo//bar")isfoo/bar,clean("foo/..")is.,clean("foo/./bar")isfoo/bar.join(a, b…)- This function uses/on Unix and\on Windows, which can be lead to unwanted behavior. The/operator, e.g.,a / b, which always uses/, should be considered as a replacement unless\s are specifically desired on Windows. Join pathawith pathb.join("foo/bar", "baz")isfoo/bar/baz. Accepts two or more arguments.
Filesystem Access
path_exists(path)- Returnstrueif the path points at an existing entity andfalseotherwise. Traverses symbolic links, and returnsfalseif the path is inaccessible or points to a broken symlink.read(path)1.39.0 - Returns the content of file atpathas string.
Error Reporting
error(message)- Abort execution and report errormessageto user.
UUID and Hash Generation
blake3(string)1.25.0 - Return BLAKE3 hash ofstringas hexadecimal string.blake3_file(path)1.25.0 - Return BLAKE3 hash of file atpathas hexadecimal string.sha256(string)- Return the SHA-256 hash ofstringas hexadecimal string.sha256_file(path)- Return SHA-256 hash of file atpathas hexadecimal string.uuid()- Generate a random version 4 UUID.
Random
choose(n, alphabet)1.27.0 - Generate a string ofnrandomly selected characters fromalphabet, which may not contain repeated characters. For example,choose('64', HEX)will generate a random 64-character lowercase hex string.
Datetime
datetime(format)1.30.0 - Return local time withformat.datetime_utc(format)1.30.0 - Return UTC time withformat.
The arguments to datetime and datetime_utc are strftime-style format
strings, see the
chrono library docs
for details.
Semantic Versions
semver_matches(version, requirement)1.16.0 - Check whether a semanticversion, e.g.,"0.1.0"matches arequirement, e.g.,">=0.1.0", returning"true"if so and"false"otherwise.
Style
-
style(name)1.37.0 - Return a named terminal display attribute escape sequence used byjust. Unlike terminal display attribute escape sequence constants, which contain standard colors and styles,style(name)returns an escape sequence used byjustitself, and can be used to make recipe output matchjust’s own output.Recognized values for
nameare'command', for echoed recipe lines,error, andwarning.For example, to style an error message:
scary: @echo '{{ style("error") }}OH NO{{ NORMAL }}'
User Directories1.23.0
These functions return paths to user-specific directories for things like configuration, data, caches, executables, and the user’s home directory.
On Unix, these functions follow the XDG Base Directory Specification.
On MacOS and Windows, these functions return the system-specified user-specific
directories. For example, cache_directory() returns ~/Library/Caches on
MacOS and {FOLDERID_LocalAppData} on Windows.
See the dirs crate for more
details.
cache_directory()- The user-specific cache directory.config_directory()- The user-specific configuration directory.config_local_directory()- The local user-specific configuration directory.data_directory()- The user-specific data directory.data_local_directory()- The local user-specific data directory.executable_directory()- The user-specific executable directory.home_directory()- The user’s home directory.
If you would like to use XDG base directories on all platforms you can use the
env(…) function with the appropriate environment variable and fallback,
although note that the XDG specification requires ignoring non-absolute paths,
so for full compatibility with spec-compliant applications, you would need to
do:
xdg_config_dir := if env('XDG_CONFIG_HOME', '') =~ '^/' {
env('XDG_CONFIG_HOME')
} else {
home_directory() / '.config'
}