Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document how to print complex strings #2446

Merged
merged 3 commits into from
Oct 31, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 35 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3583,9 +3583,9 @@ The following command will create two files, `some` and `argument.txt`:
$ just foo "some argument.txt"
```

The users shell will parse `"some argument.txt"` as a single argument, but when
`just` replaces `touch {{argument}}` with `touch some argument.txt`, the quotes
are not preserved, and `touch` will receive two arguments.
The user's shell will parse `"some argument.txt"` as a single argument, but
when `just` replaces `touch {{argument}}` with `touch some argument.txt`, the
quotes are not preserved, and `touch` will receive two arguments.

There are a few ways to avoid this: quoting, positional arguments, and exported
arguments.
Expand Down Expand Up @@ -3910,6 +3910,38 @@ fetch:
Given the above `justfile`, after running `just fetch`, the recipes in
`foo.just` will be available.

### Printing Complex Strings

`echo` can be used to print strings, but because it processes escape sequences,
like `\n`, and different implementations of `echo` recognize different escape
sequences, using `printf` is often a better choice.

`printf` takes a C-style format string and any number of arguments, which are
interpolated into the format string.

This can be combined with indented, triple quoted strings to emulate shell
heredocs.

Substitution complex strings into recipe bodies with `{…}` can also lead to
trouble as it may be split by the shell into multiple arguments depending on
the presence of whitespace and quotes. Exporting complex strings as environment
variables and referring to them with `"$NAME"`, note the double quotes, can
also help.

Putting all this together, to print a string verbatim to standard output, with
all its various escape sequences and quotes undisturbed:

```just
export FOO := '''
a complicated string with
some dis\tur\bi\ng escape sequences
and "quotes" of 'different' kinds
'''

bar:
printf %s "$FOO"
```

### Alternatives and Prior Art

There is no shortage of command runners! Some more or less similar alternatives
Expand Down