首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何通过bash中的用户输入来选择任意数量的元素?

如何通过bash中的用户输入来选择任意数量的元素?
EN

Stack Overflow用户
提问于 2021-11-05 00:58:52
回答 1查看 373关注 0票数 0

我已经创建了这个脚本,它目前正在从命令行获取一个参数列表,但我要做的是让用户传递任何数字值,然后开始执行循环,以确定用户请求的次数。脚本以以下方式运行,例如./testing.sh启动1 2 3 4 5 6 7 8。如何让用户传递一个像8这样的数值,然后在I上循环,而不是执行1 2 3 4 5 6 7 8。还有更好的方法来处理我在脚本中传递的这么多is,例如,映射它们并从文件中读取它们。

代码语言:javascript
复制
#!/bin/bash
#!/usr/bin/expect

ips=()
tarts=()

launch_tarts () {
    local tart=$1
    local ip=${ip[tart]}
    
    echo "    ----  Launching Tart $1  ----  "
        sshpass -p "tart123" ssh -Y -X -L 5900:$ip:5901 tarts@$ip <<EOF1
        export DISPLAY=:1
        gnome-terminal -e "bash -c \"pwd; cd /home/tarts; pwd; ./launch_tarts.sh exec bash\""
        exit
EOF1
}
    
kill_tarts () {
    local tart=$1
        local ip=${ip[tart]}

    echo "    ----  Killing Tart $1  ----   "
    sshpass -p "tart123"  ssh -tt -o StrictHostKeyChecking=no tarts@$ip <<EOF1
        . ./tartsenvironfile.8.1.1.0
        nohup yes | kill_tarts mcgdrv &
        nohup yes | kill_tarts server &
        pkill -f traf
        pkill -f terminal-server
        exit
EOF1
}

tarts_setup () {
    local tart=$1
        local ip=${ip[tart]}

    echo "    ----  Setting-Up Tart $1  ----   "
        sshpass -p "root12"  ssh -tt -o StrictHostKeyChecking=no root@$ip <<EOF1
        pwd
        nohup yes | /etc/rc.d/init.d/lifconfig 
        su tarts
        nohup yes | vncserver 
        sleep 10
        exit
    exit
EOF1
}

ip[1]=10.171.0.10
ip[2]=10.171.0.11
ip[3]=10.171.0.12
ip[4]=10.171.0.13
ip[5]=10.171.0.14
ip[6]=10.171.0.15
ip[7]=10.171.0.16
ip[8]=10.171.0.17
ip[9]=10.171.0.18
ip[10]=10.171.0.19
ip[11]=10.171.0.20
ip[12]=10.171.0.21
ip[13]=10.171.0.100
ip[14]=10.171.0.101
ip[15]=10.171.0.102
ip[16]=10.171.0.103
ip[17]=10.171.0.104
ip[18]=10.171.0.105
ip[19]=10.171.0.106
ip[20]=10.171.0.107

case $1 in
    kill) function=kill_tarts;;
    launch) function=launch_tarts;; 
    setup) function=tarts_setup;;
    *) exit 1;;
esac 

shift

for tart in "$@"; do
    ($function $tart) &
    ips+=(${ip[tart]})
#   echo $ips
    tarts+=(${tart[@]})
#   echo $tarts
done
wait

有人能指点一下吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-11-05 01:23:20

  • 尝试将底部循环更改为:for ((tart=1; tart<=$2; tart++)),然后使用like:./testing.sh launch 8
  • 您可以将多个变量声明放在一行上,以便将ip列表拆分为两或三列。
  • 或者使用mapfile:mapfile -t ip < ip-list。但是,您需要对数组索引使用tart - 1,比如"${ip[tart-1]}",因为数组将从0开始,而不是从1开始。
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69847552

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档