0

Would it be possible in bash to create a variable and use this variable in the pipe?

So something like this:

MYCOMMAND="ssh user@host 'tee -a Log/my.log'"
echo "Hello" | $MYCOMMAND

Doing it like the example above gives tee -a Log/my.log: No such file or directory How to do this?

Blazzter
  • 57
  • 1
  • 5
  • 1
    I suggest to use an array and no variable for this. – Cyrus Mar 01 '23 at 21:07
  • 1
    Also see [BashFAQ/050 (I'm trying to put a command in a variable, but the complex cases always fail!)](https://mywiki.wooledge.org/BashFAQ/050). – pjh Mar 01 '23 at 21:11

2 Answers2

2

This is because you try to execute the file 'tee -a Log/my.log'. You're not executing tee with -a and Log/my.log, but the whole thing as one command. And that command does not exist, hence the No such file or directory with the entire filename before it.

MYCOMMAND="ssh user@host tee -a Log/my.log" should give better results.

acran
  • 7,070
  • 1
  • 18
  • 35
Ljm Dullaart
  • 4,273
  • 2
  • 14
  • 31
1

Executing commands within commands, and as part of a downstream pipe, is doable with a bit of escaping.

One easier (?) approach would be the encapsulation of the ssh/tee in an array, eg:

$ MYCOMMAND=( ssh user@host 'tee -a Log/my.log' )
$ typeset -p MYCOMMAND
declare -a MYCOMMAND=([0]="ssh" [1]="suser@host" [2]="tee -a Log/my.log")

$ echo "Hello" | "${MYCOMMAND[@]}"
Hello

$ ssh user@host 'cat Log/my.log'
Hello
markp-fuso
  • 28,790
  • 4
  • 16
  • 36