Nils-o-mat
Nils-o-mat

Reputation: 1257

What's wrong about this Bash one-liner?

I'd be glad if you could point out, where I failed here:

line="some text"
printf "other text"|read line;printf '%s' "$line"

Output:

some text

Output I had in mind:

other text

Is this a subshell thing or am I missing something important?

Upvotes: 1

Views: 61

Answers (2)

anubhava
anubhava

Reputation: 785256

Use it like this:

read line < <(printf "other text") && printf '%s' "$line"

Upvotes: 2

user000001
user000001

Reputation: 33327

Because of the pipe, the $line variable is assigned in a subshell, and the parent shell does not record the change. You can use the shopt -s lastpipe option to execute the last command of the pipeline in the current shell

In this example, where you only print a string, you can also use this syntax:

read line <<< "other text"; printf '%s' "$line"

Or in general you can use process substitution

read line < <(printf "other text"); printf '%s' "$line"

Upvotes: 5

Related Questions