Skip to content

Instantly share code, notes, and snippets.

@ferki
Last active February 19, 2023 17:21
Show Gist options
  • Save ferki/1ba37363e88344b290f41b5b2f66aa5d to your computer and use it in GitHub Desktop.
Save ferki/1ba37363e88344b290f41b5b2f66aa5d to your computer and use it in GitHub Desktop.
Rex run with HEREDOC
use 5.26;
use Rex;
task 'heredoc_run', sub {
run 'foo', command => <<~'EOF',
f=$(cat /tmp/num)
if [ "$f" == 2 ]; then
ls -l / >/tmp/foo.txt
else
ls -l / >/tmp/bar.txt
fi
EOF
unless => <<~'EOF';
f=$(cat /tmp/num)
if [ "$f" == 2 ]; then
exit 1
else
exit 0
fi
EOF
};
@dunkeltech
Copy link

also this works:

   run "foo",
        command => <<EOF,
f=\$(cat /tmp/num)
if [ "\$f" == 2 ]; then
    ls -l / >/tmp/foo.txt
else
    ls -l / >/tmp/bar.txt
fi
EOF
        unless => <<EOF;
f=\$(cat /tmp/num)
if [ "\$f" == 2 ]; then
    exit 1
else
    exit 0
fi
EOF

which is a little bit my usecase

@ferki
Copy link
Author

ferki commented Feb 19, 2023

Yes, that should work too! 👍

run takes arguments as strings, so these could he HEREDOCs as well.

It's also possible to add single quotes in the the HEREDOC starter indicator, like <<'EOF' and then the whole HEREDOC will be treated as a string within single quotes (and this less escaping have to be done e.g. every \$ can become the more naturally readable $).

With adding v5.26, indented HEREDOCs work nicely as well with <<~'EOF' if needed. Then the whole HEREDOC and the end marker string can be indented too, leading to even more readable code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment