读取时读取里面的键盘按键

Hol*_*dad 5 bash shell-script

我有一个脚本可以搜索一些文件,其中一些带有空格,因此我正在使用while read. 在这样的循环内部,我需要使用 read -p "Pause" 来等待每次交互的按键。然而,它不是等待按键,而是读取管道的第一个字母。我需要这样的东西:

find . -name "*.o3g" | grep "pattern" | while read line
do
    process "$line"
    read -p "Press any key to continue"
done
Run Code Online (Sandbox Code Playgroud)

Sté*_*las 5

由于您已经在使用bash特定代码,因此可以执行以下操作(假设 GNUgrep或兼容):

find . -name '*.o3g' -print0 | grep -z pattern |
  while IFS= read -rd '' file; do
    process "$file"
    read -n1 -p 'Press any key to continue' < /dev/tty
  done
Run Code Online (Sandbox Code Playgroud)

(其中字符(但请注意,某些键发送多个字符)是从控制终端读取的)。

或者,更好,因为这也避免了process的 stdin 成为来自 的管道grep

while IFS= read -u 3 -rd '' file; do
  process "$file"
  read -n1 -p 'Press any key to continue'
done 3< <(find . -name '*.o3g' -print0 | grep -z pattern)
Run Code Online (Sandbox Code Playgroud)

(其中字符是从未修改的标准输入中读取的)。

另请参阅为什么循环查找的输出是不好的做法?对于处理find输出方式的其他潜在问题。

在这里,也许你可以简单地这样做:

find . -name '*.o3g' -path '*pattern*' -ok process {} \;
Run Code Online (Sandbox Code Playgroud)

另请参阅,避免除bash其自身之外的任何 GNU 主义:

find . -name '*.o3g' -exec bash -c '
  for file do
    [[ $file =~ pattern ]] || continue
    process "$file"
    read -n1 -p "Press any key to continue"
  done' bash {} +
Run Code Online (Sandbox Code Playgroud)