BASH 检查变量中是否存在
我正在编写一个用于映射网络驱动器的脚本。但是,我们只想在计算机具有特定 IP 地址时尝试映射驱动器。下面列出的是我们正在尝试运行的代码片段。
#!/bin/sh
IP="dig $HOSTNAME +short"
if [ $IP == *10.130.10.* ]; then
mount drive commands here
fi
if [ $IP == *10.130.11.* ]; then
mount drive commands here
fi
我无法让 IP 检查正常工作。有没有更好的方法来检查变量是否包含字符串(在本例中是 IP 地址的一部分)?
此帖子中列出的信息没有帮助,因为它不起作用。
I am working on a script that will be used to map network drives. However, we only want to attempt to map the drive if the machine has a particular IP address. Listed below is a code snippet that we are trying to get working.
#!/bin/sh
IP="dig $HOSTNAME +short"
if [ $IP == *10.130.10.* ]; then
mount drive commands here
fi
if [ $IP == *10.130.11.* ]; then
mount drive commands here
fi
I am not able to get the check for IP to work. Is there a better way to check to see if a variable contains a string, in this case part of an IP address?
The information listed in this posting was not helpful since it did not work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你的问题有一个“bash”标签,但 shebang 说的是 /bin/sh。您实际上想使用哪个?
事实上,首先要做的事情。您设置 IP 的方式不起作用,因为它从不运行 dig 命令;您需要反引号或
$( )
来执行此操作:现在,进行测试;有很多种方法可以做到这一点。这应该适用于所有 shell:
请注意,如果两个子网的挂载命令相同,则可以使用
*10.130.10.*|*10.130.11.*)
作为匹配模式。如果您实际上使用的是 bash,则可以使用其
[[ ]]
条件表达式来进行匹配,就像您的方式一样:如上所述,如果挂载命令相同,您可以这样做带有
if [[ "$IP" == *10.130.10.* || 的单个条件"$IP" == *10.130.10.* ]];然后。另外,在这种特殊情况下,
$IP
周围的双引号实际上并不是必需的,但我总是养成双引号变量的习惯,除非有理由不这样做。You have a "bash" tag on the question, but the shebang says /bin/sh. Which do you actually want to use?
Actually, first things first. The way you're setting IP doesn't work, since it never runs the dig command; you need either backquotes or
$( )
to do that:Now, for the test; there are a number of ways to do it. This should work in all shells:
Note that if the mount commands are the same for the two subnets, you can use
*10.130.10.*|*10.130.11.*)
as the pattern to match.If you're actually using bash, you can use its
[[ ]]
conditional expression to do the matching more like how you had it:As above, if the mount commands are the same, you can do a single conditional with
if [[ "$IP" == *10.130.10.* || "$IP" == *10.130.10.* ]]; then
. Also, the double-quotes around$IP
aren't actually necessary in this particular case, but I always make a habit of double-quoting variables unless there's a reason not to.