Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start interactive bash with predefined choice but saving interactivity

Simplest interactive script to search inside a log

#!/bin/bash
# Starting - sh /tmp/czr.sh
printf "1 - Option 1\n2 - Option 2\n";
read -r select
if [ $select = "1" ] ; then
    echo "Option 1 do nothing" ;
fi
if [ $select = "2" ] ; then
    echo -n "Type what to find: "
    read -r typed
    cat /var/log/httpd/maps_error_log | grep -i "$typed" --color
fi
exit
sh

I want to start the one with predefined option 2 like

echo "2" | sh /tmp/czr.sh

But such the command does not give an option to type what I want to find - it just opens a whole log file.

(as if echo "2" pass not only choice of "2 - Option 2" but also an "Enter" command).

Is it possible to start the bash above with preselected choice 2 but still allow to type what I want to find (saving interactivity)?

like image 430
Serge Avatar asked Nov 18 '25 07:11

Serge


1 Answers

But such the command does not give an option to type what I want to find - it just opens a whole log file.

Since both read commands normally use the same file descriptor stdin, the first read will consume input from the standard input stream. To avoid the second read from blocking or failing when stdin is empty, you should redirect it to read from an alternative source, such as /dev/tty (the terminal keyboard), which remains available even when stdin is piped.

read -r typed </dev/tty

On a side note, the cat and the | pipe is not needed, just grep the log file directly.

grep -i "$typed" /var/log/httpd/maps_error_log --color
like image 169
Jetchisel Avatar answered Nov 20 '25 10:11

Jetchisel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!