Warm tip: This article is reproduced from stackoverflow.com, please click
bash pipe scripting

How to pipe on a condition in Bash

发布于 2020-03-27 10:14:55

I'm over-complicating the problem, but is there a way of piping a command into another, given a condition on one-line in Bash?

Basically I currently have this

if [ "$check" -eq 1 ]; then
    echo -n "foo" | xclip -selection clipboard
else
    echo -n "foo"
fi

I'm wondering is there anyway in Bash to turn this into something that looks like:

echo -n "foo" && [ "$check" -eq 1 ] | xclip -selection clipboard

Where if $check == 1, "foo" will be piped into the clipboard, else the contents will be output into stdout and the pipe never activates and nothing is written into the clipboard. I want this to be a one-liner where I only call echo once.

Questioner
szybia
Viewed
134
Ed Morton 2019-07-03 21:10
$ check=0
$ echo "foo" | { if (( check == 1 )); then cat -n; else cat -; fi; }
foo

$ check=1
$ echo "foo" | { if (( check == 1 )); then cat -n; else cat -; fi; }
     1  foo