首页 > 解决方案 > 在 shell 脚本中选择 IP

问题描述

我正在编写一个 shell 脚本来部署我的主节点。为了设置节点,我想选择可用的 IP 地址,master 稍后应该监听:

PS3='Please select a network the master should listen onto: '
ips=($(hostname -I))
select ip in "${ips[@]}"
do
    case $ip in
        "Option 1")
            echo "you chose choice 1"
            ;;
        "Quit")
            break
            ;;
        *) echo "invalid option $REPLY";;
    esac
done

但是我遇到了“无效选项”。如何从我的列表中正确选择 IP 并将其进一步用作脚本中的变量?

标签: bashshellswitch-statement

解决方案


您需要匹配数字。就像是

#!/usr/bin/env bash

PS3='Please select a network the master should listen onto: '
ips=($(hostname -I))
ips=("${ips[@]}" 'Quit')
select ip in "${ips[@]}"; do
  case $ip in
    *[0-9]*)
      echo "you chose choice $REPLY with the value of $ip"
      break
      ;;
    Quit) echo quit
      break;;
    *) echo Invalid option >&2;;
  esac
done

推荐阅读