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.
$ 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
This works perfectly if the
cat -n
is changed to the clipboard. Thanks a million Ed.You're welcome. Whether the command in question is
clipboard
orcat -n
or some other command that takes piped input doesn't matter to the problem of how to conditionally pipe to a command and not everyone hasclipboard
on their system so usingcat -n
for the example is much more useful in general to readers of this forum than usingclipboard
since everyone can just copy/paste my answer to try it.