以下用于用户输入的脚本语句嵌套在 if 块下的 while 循环中,但它不起作用并且被跳过。如何让用户输入起作用?
exec 3<&0 && read -p 'Enter your answer: ' uservar <&3
FILE="hostnames.txt"
echo $(sudo chmod +777 $FILE)
echo "Step 1. Checking if file with hostnames exists."
#exec 3<&0
if [ -f "$FILE" ]
then
echo "PASSED: File hostnames.txt does exist." && echo ""
while IFS= read -r hostname;
do
echo "Step 2. Checking Grph mgmt_con_ip4 exists for $hostname"
mgmt_con_ip4="$(echo "$(llama-grph node show $hostname | grep mgmt_con_i$
echo "Grph has management IPv4 address: $mgmt_con_ip4"
if [ -z $mgmt_con_ip4 ]
then
echo "PASSED: Grph mgmt_con_ip4 == NULL" && echo ""
else
echo "FAILED: Grph mgmt_con_ip4 == NOT NULL" && echo ""
echo "$(ipam --format json get-cidr-parent $mgmt_con_ip4)" && echo ""
echo "WARNING: OOB networks shouldn't have $mgmt_con_ip4 IPv4 addres$
exec 3<&0 && read -p 'Enter your answer: ' uservar <&3
fi
done < $FILE
fi
答案1
你不应该混合read
命令和相同的file descriptor input
(FD)。在下面的例子中,我改变了最外面的read
FD=3。这是代码片段:
#!/bin/env bash
FILE="/etc/hosts"
exec 3<${FILE} 2>/dev/null || exit 1
while IFS= read -ru3 TDATA ; do
echo "${TDATA}"
echo -n "Are you sure to loop again? (y/n) "
read -rn1 YN
echo
if [[ ! ${YN} =~ ^[Yy]$ ]] ; then
echo "No more turning around."
exec 3<&- # close file
exit 1
fi
done
exec 3<&- # close file