How to regain script interactivity when `... | bash` best practices?
0
votes
0
answers
74
views
Let's say we have a simple script named
question
:
#!/bin/bash
read -rp "What's your name?" ans
echo "Your name is $ans"
Let's use cat
for our example
cat question | bash
We feed the content of the script file to the standard input of Bash and execute it as a command. When executed the standard input of bash is used, so nothing past the pipe is possible to be fed to standard in, unless put before the pipe.
To mitigate this, an option is to download the content of the script file first pass it to the shell and only then execute it.
bash -c "$(cat ./question)"
Another option I found for the syntax ... | bash
is that in the script, if we replace the current process with a new one where the stdin is redirected from the terminal, wrapped in a subshell it works, as follows:
#!/bin/bash
(
exec < /dev/tty
read -rp "What's your name?" ans
echo "Your name is $ans"
)
I wonder what other options exist there or what'd be the best practice.
Asked by punkbit
(111 rep)
Oct 6, 2023, 11:17 AM