Skip to content

Instantly share code, notes, and snippets.

@aboisvert
Last active January 18, 2021 18:51
Show Gist options
  • Save aboisvert/c6596c5715b4e085cced6c7fd6c812d2 to your computer and use it in GitHub Desktop.
Save aboisvert/c6596c5715b4e085cced6c7fd6c812d2 to your computer and use it in GitHub Desktop.
Example workaround for the lack of native "heredoc" support in fish shell
#!/usr/bin/env fish
#
# Example working with 'heredoc' documents
#
# Recommended: Define the heredoc using single quotes
#
# Use the `fish-heredoc-quote` script to generate quoted document
#
set heredoc '
unquoted text
double quoted "text"
single quoted \'text\'
singe blackslash \\
and double blackslash \\\\
that\'s it!
'
# Optional: Remove the initial/ending newlines (whitespace) from the quoting above
#
# It's important to set the internal field separator (IFS) to nil to avoid parsing
# the `heredoc` into array values after expansion e.g. avoid losing the line breaks
#
IFS="" set heredoc (string trim --left --right $heredoc)
# Assert that `heredoc` is a single string (not an array of strings)
if test (count $heredoc) != 1
echo "FAIL: Expected `heredoc` to be a single string (not an array)"
exit 1
end
# Still has line breaks!
echo $heredoc
#!/usr/bin/env fish
# Set internal field separator (IFS) to nil to avoid spliting
# the document into separate array values during parsing
# e.g. losing the line breaks
set -l IFS
# Load value into `str`
set str (cat $argv[1])
# Escape embedded backslash: \ => \\
set str (string replace -a '\\' '\\\\' $str)
# Escape embedded single quotes: ' => \'
set str (string replace -a "'" "\'" $str)
echo $str
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment