gpt4 book ai didi

linux - Bash-Shell 脚本中止且没有错误

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:22 27 4
gpt4 key购买 nike

在 Debian 上,以下代码可以正常工作,但在 CentOS 上,它只是中止,没有任何错误。错误是什么?我无法理解。

    echo "Test 1"
ANSWER=""
read -p "Enter y or n " ANSWER;
echo "Test 2"

输出看起来总是这样:

    Test 1

我还尝试了不带参数 -p 的读取命令,但这也不起作用:

    echo "Test 1"
ANSWER=""
echo "Enter y or n "
read ANSWER;
echo "Test 2"

输出:

    Test 1
Enter y or n

如果我在命令行执行该命令,它是否有效,应该如何工作。该脚本具有以下“标题”:#!/bin/bash

有人可以帮忙吗?

最佳答案

@ user2966991 - 从标准输入读取的脚本位于一个更大的 while 循环内,该循环通过标准输入读取文件。这是行不通的。尝试将您的标准输入重定向到不同的文件处理程序。

考虑这个示例代码。这将不起作用,因为 while 循环和 read 都是从 stdin 读取。

#!/bin/bash
cat samplefile | while read line; do
read -p "$line (y/n)?" ANSWER
done

现在考虑其他代码。

#!/bin/bash
# save stdin to file descriptor 5
exec 5<&0

cat samplefile | while read line; do
read -p "$line (y/n)?" ANSWER <&5
done

# restore stdin and close file descriptor 5
exec 0<&5 5>&-

就我个人而言,我更喜欢输入重定向而不是管道。

cat file | while read var; do
...
done

可以写成

while read var; do
...
done < file

下次请在此处发布您的脚本,否则您将不会得到任何答案。

关于linux - Bash-Shell 脚本中止且没有错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com