5

I desire to run a cat heredocument in a single row instead the natural syntax of 3 rows (opener, content, and delimiter). My need to do so is mostly aesthetic as the redirected content aimed aimed to be part of a handbook text file and I would like to save as much rows as I can, in that particular file).

Doing cat <<< TEST > ~/myRep/tiesto tiesto TEST (what I would normally split for 3 parts) results in an errors:

tiesto: No such file or direcotry

TEST: No such file or directory.

Is it even possible to execute one-row heredocuments in Bash?

2 Answers2

13

Yes, but you'd be using a an here-string rather than a here-document:

cat >"$HOME/myRep/tiesto" <<<'tiesto'

This will send the string tiesto to cat on its standard input, and it will write the string to the file $HOME/myRep/tiesto through a redirection of its standard output.

Note that here-strings are not standard but are implemented by at least zsh (where it comes from, at the same time as the UNIX version of rc, though that rc and its derivatives like es or akanga don't add an extra newline character in the end), ksh93, bash, mksh and yash.

Kusalananda
  • 333,661
2

You could put a here-document (as opposed to a here-string), on a single line, by using:

eval $'cat << TEST > ~/myRep/tiesto\ntiesto\nTEST'

Technically, that's one line of code, but the $'...' will expand into a new 3 line code that is evaluated again.

Using eval, you can always put any shell code on one line.

With shells that don't support $'...', you can do:

eval "$(printf 'NL="\n"')"; eval "cat << TEST > ~/myRep/tiesto${NL}tiesto${NL}TEST"

Or

eval "$(printf 'cat << TEST > ~/myRep/tiesto\ntiesto\nTEST')"

Of course here,

echo tiesto > ~/myRep/tiesto

would be a lot simpler. Or for multiple lines:

printf '%s\n' "line 1" "line 2" > ~/myRep/tiesto
  • this is slightly more clear to me: eval $'cat << DL > /home/user/test \nLine1\nLine2\nDL' (DL is the delimiter in a Heredoc cat << EOF > file.txt \nLine1\nLine2\nEOF https://linuxize.com/post/bash-heredoc/) $'..' is an ANSI C string https://unix.stackexchange.com/questions/48106/what-does-it-mean-to-have-a-dollarsign-prefixed-string-in-a-script "Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard." – alchemy Aug 01 '23 at 03:18