gpt4 book ai didi

linux - 在 bash 脚本中替换变量的可选参数

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:37:15 24 4
gpt4 key购买 nike

如何将可选参数传递给 bash 脚本以替换脚本中的现有变量?例如:

#!/bin/bash
#hostfinder.sh
#Find hosts in current /24 network

subnet=$(hostname -i | cut -d. -f1,2,3)

for j in \
$(for i in $subnet.{1..255}; do host $i; done | grep -v not | cut -d" " -f5)
do ping -c1 -w 1 $j; done | grep -i from | cut -d" " -f3,4,5 | tr ':' ' ' | \
sed -e 's/from/Alive:/'

这将获取当前主机的 IP,对可能的邻居运行反向查找,对它找到的任何主机名进行 ping 测试,并显示类似于此的输出:

Alive: host1.domain (10.64.17.23)
Alive: host2.domain (10.64.17.24)
...

叫我疯了,但它比 nmap 快得多,而且会生成一个不错的列表。

无论如何,在执行脚本时,我想选择性地将任何 C 类网络地址的前三个八位字节作为 $1 参数传递给 $subnet 变量。例如:

./hostfinder.sh 10.20.0

我的第一个想法是尝试类似 $subnet=$1 的方法,但我认为这不会起作用。我对重写脚本以使其更优雅或其他任何东西并不感兴趣,我主要只是对我在主题行中输入的内容感到好奇。

最佳答案

如何替换:

subnet=$(hostname -i | cut -d. -f1,2,3)

与:

case $# in  
0) subnet=$(hostname -i | cut -d. -f1,2,3);;
1) subnet="${1}";;
*) echo "To many arguments" >&2; exit 1;;
esac
  • $#是命令行参数个数
  • 这不如 getopt 优雅,但易于理解和扩展。

关于linux - 在 bash 脚本中替换变量的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15381602/

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