简体   繁体   English

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

[英]Optional argument to replace variable in bash script

How can I pass an optional argument to a bash script that will replace an existing variable in the script? 如何将可选参数传递给将替换脚本中现有变量的bash脚本? For example: 例如:

#!/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:/'

This will grab the IP of the current host, run a reverse lookup against possible neighbors, ping test any hostnames it finds, and display an output similar to this: 这将获取当前主机的IP,对可能的邻居进行反向查找,对发现的所有主机名执行ping测试,并显示类似于以下内容的输出:

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

Call me crazy, but it's way faster than nmap and spits out a nice list. 叫我疯了,但是它比nmap快得多,并且列出了不错的列表。

Anyway, I'd like to optionally pass the first three octets of any class C network address to the $subnet variable as the $1 argument when executing the script. 无论如何,我想在执行脚本时有选择地将任何C类网络地址的前三个八位字节作为$ 1参数传递给$ subnet变量。 For example: 例如:

./hostfinder.sh 10.20.0

My first thought was to try something like $subnet=$1, but I assume that will not work. 我的第一个想法是尝试使用$ subnet = $ 1之类的方法,但是我认为那将行不通。 I'm not really interested in re-writing the script to be more elegant or anything, I am mostly just curious about what I put in the subject line. 我对重新编写脚本以使其更优雅或更不感兴趣,我只是对我在主题行中输入的内容感到好奇。

How about replace: 如何更换:

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

with: 与:

case $# in  
  0) subnet=$(hostname -i | cut -d. -f1,2,3);;
  1) subnet="${1}";;
  *) echo "To many arguments" >&2; exit 1;;
esac
  • $# is the number of command line arguments $#是命令行参数的数量
  • This is less elegant as getopt but easy to understand and extend. getopt它不那么优雅,但易于理解和扩展。

尝试使用getopt从命令行中的选项中读取,然后设置变量。

Like LtWorf suggested, try using getopt . 就像LtWorf建议的那样,尝试使用getopt Its read the options and its arguments from the command line. 它从命令行读取选项及其参数。

You can find a great example of getopt usage here: getopt usage example 你可以找到一个很好的例子getopt位置用法: getopt的使用示例

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM