Just:
variable=$(
{
printf 'scan on\n\n'
sleep 10
printf 'quit \n\n'
} | bluetoothctl
)
The inside of command substitutions can be any shell code¹ and doesn't have to be on one line.
Here, you want to capture the output of the whole pipeline (in effect, that will be the output of bluetoothctl
since all the other commands have their stdout redirected to the pipe that goes to bluetoothctl
).
You could also capture the output of bluetoothctl
only with:
{
printf 'scan on\n\n'
sleep 10
printf 'quit \n\n'
} | variable=$(bluetoothctl)
But in bash
, for that to work, you'd need to set the lastpipe
option (shopt -s lastpipe
, only works for non-interactive shell instances), for that last pipe component not to be run in a subshell.
Here however, you don't need the pipeline, you can just do:
variable=$(bluetoothctl --timeout 10 scan on)
If you're going to display the contents of the variable, remember the syntax is:
printf '%s\n' "$variable"
not echo $variable
.
More details on that at:
Here the output of bluetoothctl
contains colouring escape sequences as well as escape sequences used to clear the contents of lines. If you leave $variable
unquoted, its contents will be subject to split+glob resulting in a random list of words to pass to echo
which echo
will output space-separated. So you'll end up with everything on one line and if the last word ends in a clear-line sequence (which it does in my tests: \r\e[K
being Carriage-Return followed by the Clear-To-End-Of-Line sequence), you'll just see a blank line.
¹ though some shells including bash
used to choke on code with unmatched parenthesis like when the code included case statements like case $x in foo)
or comments with unbalanced )
which the shell parser was mistaking for the )
closing the command substitution.
shopt -s lastpipe
before it, but output is missing on some places and is weirdly only on one line. I don't know if I did something wrong – cheshire Dec 04 '20 at 15:56echo $variable
instead ofprintf '%s\n' "$variable"
. See Why is printf better than echo? and When is double-quoting necessary? – Stéphane Chazelas Dec 04 '20 at 16:02;
ornewline
to separate the command substitutions will not make any difference in that case. Whether usingecho
will cause problem or not in that case depends on a number of parameters detailed in the Q&A I linked to. Usingecho
to output arbitrary data is bad practice in general. – Stéphane Chazelas Dec 04 '20 at 16:10