Last active
January 18, 2021 18:51
-
-
Save aboisvert/c6596c5715b4e085cced6c7fd6c812d2 to your computer and use it in GitHub Desktop.
Example workaround for the lack of native "heredoc" support in fish shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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