在日志中搜索的最简单的交互式脚本
#!/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
我想启动一个预定义选项 2 的
echo "2" | sh /tmp/czr.sh
但是这样的命令没有提供输入我想要查找的内容的选项 - 它只是打开整个日志文件。
(好像 echo“2”不仅传递了“2 - 选项 2”的选择,还传递了“Enter”命令)。
是否可以使用预选选项 2 来启动上面的 bash,但仍允许输入我想要查找的内容(保存交互性)?
由于两个
read
命令通常使用相同的文件描述符stdin
,因此第一个命令read
将从标准输入流中获取输入。为了避免第二个命令在 为空read
时阻塞或失败,您应该将其重定向到其他来源,例如(终端键盘),即使为空,该来源仍然可用。stdin
read
/dev/tty
stdin
顺便说一句,不需要管道,只需要
cat
日志文件。|
grep
询问用户第二个问题的答案,并将其传送给脚本。