如何在while循环变为true后退出bash脚本?
我是bash脚本新手,我正在尝试编写一个脚本来检查以太网设备是否启动,如果启动了,请退出脚本。 这不符合预期,也许有人能给我一个提示 我启动脚本,然后插入设备,脚本似乎挂在终端上。它不会返回到命令行如何在while循环变为true后退出bash脚本?,bash,shell,Bash,Shell,我是bash脚本新手,我正在尝试编写一个脚本来检查以太网设备是否启动,如果启动了,请退出脚本。 这不符合预期,也许有人能给我一个提示 我启动脚本,然后插入设备,脚本似乎挂在终端上。它不会返回到命令行 #! /bin/sh t1=$(ifconfig | grep -o enxca1aea4347b1) t2='enxca1aea4347b1' while [ "$t1" != "$t2" ]; do sleep 1; done echo "Connected" exit 0 当设备已经
#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
sleep 1;
done
echo "Connected"
exit 0
当设备已经插入并且ethernet dev启动时,脚本就可以完美地运行。然后,它回显“已连接”,并将我扔回命令行
#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
sleep 1;
done
echo "Connected"
exit 0
由于没有在while语句中更新
$t1
的值,因此您创建了一个无限循环
相反,请尝试:
#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
sleep 1;
t1=$(ifconfig | grep -o enxca1aea4347b1)
done
echo "Connected"
exit 0
由于没有在while语句中更新
$t1
的值,因此您创建了一个无限循环
相反,请尝试:
#! /bin/sh
t1=$(ifconfig | grep -o enxca1aea4347b1)
t2='enxca1aea4347b1'
while [ "$t1" != "$t2" ];
do
sleep 1;
t1=$(ifconfig | grep -o enxca1aea4347b1)
done
echo "Connected"
exit 0
你甚至不需要做比较;只需检查
grep
的退出状态
t2='enxca1aea4347b1'
until ifconfig | grep -q "$t2"; do
sleep 1;
done
echo "Connected"
exit 0
事实上,您甚至不需要grep
:
until [[ "$(ifconfig)" =~ $t2 ]]; do
sleep 1
done
你甚至不需要做比较;只需检查
grep
的退出状态
t2='enxca1aea4347b1'
until ifconfig | grep -q "$t2"; do
sleep 1;
done
echo "Connected"
exit 0
事实上,您甚至不需要grep
:
until [[ "$(ifconfig)" =~ $t2 ]]; do
sleep 1
done
您可以使用
grep
的退出值来决定循环是否应该退出谢谢!!!现在你提到它,我意识到我的错误:D case closed你可以使用grep
的退出值来决定循环是否应该退出谢谢!!!现在您提到了它,我意识到了我的错误:D case closed注意[[]]
是一个bash扩展,不受所有其他shell的支持。如果你想用这个,把shebang改成#/bin/bash
或它可能(或可能不)失败。请注意,[[]]
是bash扩展,不受所有其他shell的支持。如果你想用这个,把shebang改成#/bin/bash
或它可能(或可能不)失败。