3

I'm trying to run a script that takes a -t argument. This argument stands for text, and the value -- in theory -- is allowed to be multiline. On the command line, I assume a Here Document would work, but I don't like typing out long things on the command line. In addition, I want this file to persist so I can pass it again later.

I'm not sure how to do this; if I cat foo | xargs echo, it prints as one line. This fixes that: cat foo | xargs -d='' echo, but it makes me think there are things I don't understand that will change the whitespace or general structure of the document depending on its contents.

How do I pass a multiline file as an argument without having to worry about special chars or changing its format?

  • 1
    There are "here documents" but I have never heard of "from documents". It looks like you just need some-command -t "$(cat foo)" – muru Aug 17 '21 at 03:25
  • @muru lol, sorry that's what I meant. To me that name is so arbitrary I can never remember it. – Daniel Kaplan Aug 17 '21 at 04:16

2 Answers2

5
  1. Why not just pass it a filename? If the script doesn't already know how to deal with filenames, modify it so that it does (e.g. by treating all unknown arguments as filenames, and/or by adding a -f option for input filenames). Remember to add error-checking code and respond appropriately when a filename doesn't exist, or can't be read due to permissions, etc.

  2. Quote your argument. e.g. -t "$(cat foo)"

cas
  • 78,579
  • I'd like to, but the script is way over my head. I could modify it for my personal use, but I think I'd have to spend a day learning bash to contribute back to the repo. I'd rather do the latter some day ™
  • – Daniel Kaplan Aug 17 '21 at 04:24
  • BTW, how do I learn why "$(cat foo)" is safe for any file contents? – Daniel Kaplan Aug 17 '21 at 04:25
  • 5
    @DanielKaplan Any file contents? No. (1) "$(cat foo)" removes all newlines from the very end. (2) In Bash you cannot pass NUL bytes this way. But since your script expect text, you shouldn't pass NUL bytes (by definition the text file does not contain NUL). (3) Argument list too long is possible. // The right way to pass arbitrary content is not via the command line. The script should work with a file: stdin or a named file (the name specified in the command line, environment, config or hardcoded). – Kamil Maciorowski Aug 17 '21 at 04:48
  • @KamilMaciorowski Agreed. I created an issue for that. – Daniel Kaplan Aug 17 '21 at 05:49