Motivation: I often open a remote shell on android devices (using adb
/ Android debug bridge), and want to write scripts on my machine (not android devices, because I have multiple) to help me when i first connect into the shell.
For example, I might want to change directory into a specific folder,
echo "cd /storage/self/primary/Download; mkdir bobby" | adb shell
, however the stdin in immediately closed once the code is executed, and the shell is immediately closed too. I've added mkdir bobby
just to test that the line is actually executed, and it is.
For example, the shell will automatically close in 5 seconds when I run echo "cd /storage/self/primary/Download; mkdir bobby; sleep 5" | adb shell
. Unfortunately, a heredoc doesn't help, because it will also close the shell once the heredoc delimiter is found.
Question: How do I keep stdin connected to terminal after piping a command into it, so that I can type into it. This is not a challenge with ssh
, because you can directly pass an optional command.
Apologies if this question has already asked, I wasn't sure how to phrase it.
答案1
To keep the pipe open, don't let it close. You may do this by adding cat
to the left hand side in the pipe:
{ echo "cd /storage/self/primary/Download; mkdir bobby"; cat; } | adb shell
The cat
process will execute after echo
, and have its standard output connected to the adb shell
command, while its standard input reads from the terminal (where you may type).
As soon as cat
terminates (by you pressing either Ctrl+C to interrupt, or Ctrl+D to signal end of input) the pipeline will terminate.
Note that this may not give you a full interactive shell with a prompt and command line completion or whatever other interactive features the adb shell
command provides normally, but will let you send commands to the right hand side of the pipe.
This is similar to what's explained in What is meant by "keeping the pipe open"?