如何同时运行 Bashscript 的两部分代码,其中一部分是无限循环

如何同时运行 Bashscript 的两部分代码,其中一部分是无限循环

我有这个 bash 脚本代码,我想在 while 循环中并排运行 read 命令,因为 read 命令从用户那里获取数据并将其保存在某个文件中,而 while 循环则检查相关的东西,所以有什么建议,比如在两个终端上都执行它们或类似的东西

谢谢

 #!/bin/bash 
    trap "echo \"\" > /home/........./file.txt"  SIGINT SIGTERM SIGHUP
    while sleep 2
do
read -s -n 1 key   
    if [[ $key = "" ]]; then 
        echo >> somefile
    else
        echo "You pressed '$key'"
    fi
clear
done
    while sleep $sleepInterval
    do
    i=0
    while read line
    do
    somecommands
    done

答案1

我是这样做的:

#!/bin/bash

a=0

function ACTION ()
{
if [[ "$bb" == "Q" || "$bb" == "q" ]]; then
    echo "Good bye!"
    exit 0
else 
    echo -e "\n\nYou pressed $bb.\n\n"
fi
}

while true; do
    read -t 1 -n 1 bb && ACTION
    echo -ne "Hello $a times. Hit \"q\" to quit."'\r' 
    a=`echo "$a + 1" | bc`
done
exit 0

这就是已回答堆栈溢出经过安迪并且在这里工作得很好。

脚本是他的(我只是添加了陷阱部分,因为他说如果脚本被杀死,终端将处于奇怪的状态):

#!/bin/bash

trap 'echo -e "\n\n############\n#          #\n# Bye bye  #\n#          #\n############\n" && exit 1' INT 
trap 'notify-send "Bye bye" "The terminal has been closed" && exit 1' HUP

if [ ! -t 0 ]; then
  echo "This script must be run from a terminal"
  exit 1
fi

stty -echo -icanon time 0 min 0

count=0
keypress=''
while true; do
  let count+=1
  echo -ne $count'\r'

  # This stuff goes in _handle_keys
  read keypress
  case $keypress in
  # This case is for no keypress
  "")
    ;;
  $'\e[C')
    echo "derecha"
    ;;
  $'\e[D')
    echo "izquierda"
    ;;
  # If you want to do something for unknown keys, otherwise leave this out
  *)
    echo "unknown input $keypress"
    ;;
  esac
  # End _handle_keys
done

stty sane

答案2

我会让 inf. 循环成为它自己单独的脚本然后当我运行它时在它后面放一个 & 符号

/bin/bash #!/bin/bash
猫/ var /日志/ dmesg
〜/ inf-loop.sh&
ls /var/cache/apt/archive/*.deb

相关内容