pipe the read command?

I’m trying to pipe a string with special characters (e.g. HG@eg3,l'{TT"C! to another command (termux-clipboard-set) with the read program. It seems that read was designed to create a temporary variable (e.g. read temp) that should be then passed to another command (e.g. termux-clipboard-set $temp).

I’m wondering if there is a faster way to do it with a pipe, like: read | termux-clipboard-set?

UPDATE: Sorry, I forgot to mention that I’m looking for something that would work on bash (termux).

Asked By: Daniel Krajnik


In zsh, where the read builtin supports a -e option for echo:

termux-clipboard-set "$(IFS= read -re)"

If your system still has a line command (there’s still one in util-linux but it’s generally not included these days), with any POSIX-like shell:

termux-clipboard-set "$(line)"

That line command could be written as a sh function as:

line() (
  IFS= read -r line; ret=$?
  printf '%sn' "$line"
  exit "$ret"

head -n 1 does something similar except that when not reading from a terminal most implementations would read by blocks┬╣ and then may read more than a line from their input even if they output only one line. read and line are guaranteed not to (though you need to make sure to use the -r option for read).

With input coming from a terminal,

termux-clipboard-set "$(head -n1)"

Should work though. Most head implementations still also support the obsolete (but shorter) head -1.

With tcsh, that’s:

termux-clipboard-set $<:q

┬╣ they also read by blocks from terminal devices, but read()s on terminal devices in icanon mode don’t return more than one line.

Answered By: Stéphane Chazelas

For bash, read is not a program. read is a builtin. Simplified, read reads stdin and assigns that input to a variable. The read builtin does not produce any output on stdout, so trying to pipe stdout to something does not produce anything.

The question is why. According to the man page,

Usage termux-clipboard-set [text]

Text is read either from standard input or from command line arguments.

If text is read from stdin, why would you want to put something in front? Sure, you could cat | termux-clipboard-set, but just termux-clipboard-set would do the trick.

Answered By: Ljm Dullaart
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.