带有case语句和循环的Shell脚本不工作

Posted

技术标签:

【中文标题】带有case语句和循环的Shell脚本不工作【英文标题】:Shell script with case statement and loop for not working 【发布时间】:2021-10-21 06:54:10 【问题描述】:

尝试在服务器列表中连接并执行一些命令,此脚本不执行第二步 (AIX)

SO=uname -s

用于 $(cat maq) 中的服务器 做

case $SO in

Linux)
    echo "Connecting in $server"
    ssh  $server 
    echo "my system is $SO" 
    "exit"
    ;;

AIX)
   echo "Connecting in $server"
   ssh  $server
   echo "my system is $SO"
   "exit"
   ;;

esac

完成

他们为所有情况选择执行“我的服务器是 Linux”!有什么帮助吗?

【问题讨论】:

既然你在做同样的事情,为什么还要写case? :-) 你的意思是case $server in ... 【参考方案1】:

(已编辑以使其更清晰)

您似乎将本地操作系统与远程操作系统混淆了。前者在循环期间不会改变,只有后者。这是一个完整的例子。

LocalOs="$(uname -s)"
case "$LocalOs" in
Linux)
    echo "Local OS is $LocalOs";
    ;;
AIX)
    echo "Local OS is $LocalOs";
    ;;
*)
    echo "Local OS is $LocalOs";
    ;;
esac

while read server; do
    RemoteOs=$(ssh </dev/null "$server" 'uname -s')
    case "$RemoteOs" in
    Linux)
        echo "OS on $server is $RemoteOs"
        ;;
    AIX)
        echo "OS on $server is $RemoteOs"
        ;;
    *)
        echo "OS on $server is $RemoteOs"
        ;;
    esac
done <"maq"

编辑:您也误解了ssh 在脚本中的工作方式。这不起作用:

ssh remoteuser@remotehost
commands to be executed on remotehost
exit

这行得通:

ssh remoteuser@remotehost <<EOF
commands to be executed on remotehost
EOF

更简单的情况:

ssh remoteuser@remotehost 'command(s) to be executed on remotehost'

【讨论】:

你好朋友,不,我需要通过 SO 类型测试 e 发送命令!案例 Linux 或案例 AIX

以上是关于带有case语句和循环的Shell脚本不工作的主要内容,如果未能解决你的问题,请参考以下文章

Shell脚本应用(forwhile循环语句和case分支语句)

Linux丨shell语句while和until和case使用

浅谈Shell脚本中for循环while循环及case分支语句

Shell脚本 for循环 while循环 case分支语句

shell中case语句程序传参while

Shell脚本(forwhile和case语句的应用示例)