You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Bash脚本参数判断问题:按参数SSH连接不同服务器

Fixing Your SSH Connection Bash Script Issues

Let's break down the problems in your script and fix them step by step:

1. Why you're getting "integer expression is expected"

Your first condition uses -eq, which is an integer comparison operator—it only works for comparing numbers, not regular expressions. On top of that, the [ test command doesn't support regex matching at all. Your regex syntax was also off (the comma in ^[1,3-5]$ is unnecessary; it should be ^[13-5]$ to match 1, 3, 4, or 5).

2. Why it always connects to servername2

Your second condition [ $1=h ] has two critical issues:

  • No spaces around the =! In Bash, [ is a command, so all parameters (like $1, =, h) need to be separated by spaces. Without spaces, $1=h gets treated as a single non-empty string, which [ evaluates as true every time (unless you pass no arguments).
  • You should use proper string comparison syntax—either = with [ (with spaces) or == with [[ for cleaner, more reliable checks.

Here's the corrected script

#!/bin/bash

# First, check if any argument was provided
if [ $# -eq 0 ]; then
    echo "Error: Please provide an argument. Valid options: 1, 3-5, or h"
    exit 1
fi

# Match valid numeric arguments (1, 3, 4, 5)
if [[ $1 =~ ^[13-5]$ ]]; then
    ssh -X servername1"$1"
# Match the 'h' argument
elif [[ $1 == "h" ]]; then
    ssh -X servername2
# Handle invalid arguments
else
    echo "Error: Invalid argument. Valid options: 1, 3-5, or h"
    exit 1
fi

Key improvements explained:

  • Added a check for missing arguments to avoid unexpected errors when running the script without input.
  • Used [[ ... =~ ... ]] for regex matching (this is Bash's native way to handle regular expressions). The regex ^[13-5]$ ensures the input is exactly one of 1, 3, 4, or 5.
  • Used [[ $1 == "h" ]] for clean string comparison, with proper spacing and a quoted literal to avoid edge cases.
  • Added an else branch to give clear feedback for invalid inputs, so the user knows exactly what went wrong.

内容的提问来源于stack exchange,提问作者Renat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:22:16