【问题标题】:Bash script echo and no need to press ENTERBash 脚本回显,无需按 ENTER
【发布时间】:2017-02-13 22:36:18
【问题描述】:

编辑:当前代码

#!/bin/bash
check=0

while [ $check -ne 1 ];
do
        ping -c 1 192.168.150.1 >> /dev/null
        if [ $? -eq 0 ];then
            echo -ne "\nClient is up! We will start the web server"
            touch /etc/apache2/httpd.conf
            echo "ServerName 127.0.0.1" > /etc/apache2/httpd.conf
            /etc/init.d/apache2 start
            if [ $? -eq 0 ];then
            exit 0
            fi
        else
            echo -ne "\nWaiting for client to come online"
            sleep 5;
        fi
done

我目前正在学习一些 Bash 脚本,我希望能够将其回显到终端,而无需按 Enter 键即可继续使用终端。

例如...如果我回显“我们正在工作”,光标将移动到末尾并等待我按 Enter 键,然后将我返回到可以键入新命令的位置。

server:#
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online
Waiting for client to come online <---- Press Enter here
server:#

【问题讨论】:

  • 你能给我们看看代码吗?
  • @ArkadiuszDrabczyk 我已经用当前代码编辑了帖子。
  • 你为什么要appending (&gt;&gt;)到NULL对象?
  • @123 我没有使用读取,我希望它打印然后继续终端输入,此时它只是回显到命令行中。
  • 你是如何运行代码的?我怀疑你是在后台运行它,并且 shell 已经在接受一个新命令;该脚本只是将输出写入您的终端,直到它退出。

标签: linux bash


【解决方案1】:

使用回声“^M”。

引号里面的字符是按crtl+v+m形成的。

它应该可以工作。

这个角色将完成输入的工作。

更新:

我刚刚在我的 shell 上试​​了一下。我能够获得额外的输入。您可能需要在此之后添加另一个 echo 命令。

我们使用“od -c”(如下图)来检查字符是否正确。

使用正确的字符,我们在 od -c 输出中得到“\r \n”。在不恰当的情况下,我们得到 ^ M。

正确:

Wed Oct 05|19:03:45|app/ga> echo "^M"|od -c
0000000  \r  \n
0000002

不当:

Wed Oct 05|19:03:50|app/ga> echo "^M"|od -c
0000000   ^   M  \n
0000003
Wed Oct 05|19:03:57|app/ga>

验证后,请使用此行再次尝试,而不是脚本中的行。

echo -ne "\nWaiting for client to come online" ; echo "^M"

在键盘上按 ctrl+v+m 可以正确形成“^M”字符。

干杯, 高拉夫

【讨论】:

  • 这并没有解决问题。我现在得到“等待客户上线^M”,同样的问题仍然存在:(
  • 只需要了解输入的输入方式和位置。我想我不清楚这一点。你能帮忙吗?
  • 嗨,Nathan,请再次检查我的解决方案,我已经添加了一些关于如何检查字符是否正确的 cmets 以及您的脚本中的一个小改动。谢谢。
【解决方案2】:

我怀疑您的问题与使用 echo -ne '\n...' 而不是简单的 echo '...' 有关。但是,您的整个代码可以大大简化:

#!/bin/bash

while :; do
    until ping -c 1 192.168.150.1 > /dev/null; do
        echo "Waiting for client to come online"
    done
    echo "Client is up! We will start the web server"
    echo "ServerName 127.0.0.1" > /etc/apache2/httpd.conf
    /etc/init.d/apache2 start && break
done

【讨论】:

  • 太棒了!在我们等待客户出现时,问题仍然存在。这是因为 while 循环正在运行,我希望它回显到终端,然后就是这样,就好像脚本在后台运行一样。
  • 当你运行脚本时,在...之后添加一个&amp; 所以假设脚本被称为script.sh,然后只需在终端中输入:script.sh &amp;.. 这将运行它背景。
猜你喜欢
  • 2015-05-11
  • 2014-07-27
  • 2020-09-23
  • 1970-01-01
  • 1970-01-01
  • 2014-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多