强制Bash-Script等待等待输入的Perl脚本

时间:2018-02-07 17:16:31

标签: bash perl user-input

我有一个Bash-Script,它顺序运行一些从文件中读取的Perl-Scripts。这些脚本需要按Enter键才能继续。

奇怪的是,当我运行脚本时,它从不等待输入但只是继续。我假设Bash-Script中的某些内容被解释为Enter或其他一些按键,并使Perl继续。

我确定那里有一个解决方案,但我真的不知道该寻找什么。

My Bash有这个while-Loop,它遍历Perl-Scripts列表(列在seqfile中)

while read zeile; do
    if [[ ${datei:0:1} -ne 'p' ]]; then
        datei=${zeile:8}
    else
        datei=$zeile
    fi
    case ${zeile: -3} in
    ".pl")
    perl  $datei  #Here it just goes on...
    #echo "Test 1"
    #echo "Test 2"
    ;;
    ".pm")
        echo $datei "is a Perl Module" 
    ;;
    *)
        echo "Something elso"
    ;;
    esac
done <<< $seqfile;

您注意到echo "Test 1/2"这两个注释行。我想知道它们是如何显示的。 实际上,他们是互相写下来的,就像有一个Enter-Press:

Test 1
Test 2

Perl-Scripts的输出是正确的我只需要弄清楚如何强制从用户而不是从脚本中读取输入。

2 个答案:

答案 0 :(得分:3)

让perl脚本重定向来自/dev/tty

概念证明:

while read line ; do
    export line
    perl -e 'print "Enter $ENV{line}: ";$y=<STDIN>;print "$ENV{line} is $y\n"' </dev/tty
done <<EOF
foo
bar
EOF

节目输出(用户输入粗体):

Enter foo: 123 foo is 123
Enter bar: 456 bar is 456

答案 1 :(得分:3)

@mob的答案很有意思,但我想为你的用例提出一个替代解决方案,如果整个bash脚本使用特定的输入重定向运行也可以工作(即不是{ {1}})。

最小的工作示例:

  • script.perl

    /dev/tty
  • script.bash

    #!/usr/bin/env perl
    use strict;
    use warnings;
    {
        local( $| ) = ( 1 );
        print "Press ENTER to continue: ";
        my $resp = <STDIN>;
    }
    print "OK\n";
    

因此,这适用于终端中的#!/bin/bash exec 3>&0 # backup STDIN to fd 3 while read line; do echo "$line" perl "script.perl" <&3 # redirect fd 3 to perl's input done <<EOF First Second EOF exec 3>&- # close fd 3 ./script.bash,例如......

有关重定向的详细信息,请参阅例如this articlethis cheat sheet

希望这有帮助