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

Bash脚本prova.sh执行异常:输入-h未仅输出帮助信息

问题描述

我编写了简单脚本prova.sh:

#!/bin/bash
echo "\$# = [$#]"

echo "\$1 = [$1]"

if [ $# -ge 2 || $1="-h" ]
then
echo "#########################################################################"
echo -e "usage: $0 \t launches the program only"
echo -e "       $0 -s\t shows the command fired and launches the program"
echo -e "       $0 -so\t shows only the command fired"
echo -e "       $0 -h\t shows this guide"
echo "#########################################################################"
exit 0
fi

command="ls -la"

if test "$1"="-so" || "$1"="-s"
then
        echo "Fired command:"
        echo $command
fi


if test "$1"!="-so"
then
        $command
fi

执行./prova.sh -h后的输出如下:

$> ./prova.sh -h

$# = [1]

$1 = [-h]

./prova.sh: row 6 : [: "]" missing

./prova.sh: row6: -h=-h: command not found

Fired command:
ls -l

totale 4

-rwxrw-r--. 1 user user 632 20 lug 16.13 prova.sh

预期执行该命令后仅输出帮助信息,但实际结果不符,请求排查问题。


问题排查与修正

你的脚本存在几处Bash语法问题,导致逻辑没有按预期执行,具体修正点如下:

1. if [ ... ]条件判断的语法错误

Bash中,单中括号[ ... ]本质是test命令的别名,它不支持||作为逻辑或,需要用-o;同时字符串比较的=前后必须加空格,否则会被解析成单个字符串,无法完成比较。
原代码:

if [ $# -ge 2 || $1="-h" ]

推荐改用Bash原生的双中括号[[ ... ]],它支持||逻辑或,语法更宽松直观:

if [[ $# -ge 2 || "$1" == "-h" ]]

如果坚持用单中括号,修正为:

if [ $# -ge 2 -o "$1" = "-h" ]

2. test命令的语法问题

test命令中,字符串比较的=/!=前后必须加空格,逻辑或要用-o(或者拆分两个test命令用||连接)。原代码里的"$1"="-so"会被当成一个非空字符串,导致条件恒为真;而"$1"="-s"会被当成命令执行,直接报错。
原代码:

if test "$1"="-so" || "$1"="-s"

修正为(用-o):

if test "$1" = "-so" -o "$1" = "-s"

或者用双中括号更简洁:

if [[ "$1" == "-so" || "$1" == "-s" ]]

同样,另一个test判断的错误:

if test "$1"!="-so"

修正为:

if test "$1" != "-so"

或双中括号:

if [[ "$1" != "-so" ]]

修正后的完整脚本

#!/bin/bash
echo "\$# = [$#]"

echo "\$1 = [$1]"

if [[ $# -ge 2 || "$1" == "-h" ]]
then
echo "#########################################################################"
echo -e "usage: $0 \t launches the program only"
echo -e "       $0 -s\t shows the command fired and launches the program"
echo -e "       $0 -so\t shows only the command fired"
echo -e "       $0 -h\t shows this guide"
echo "#########################################################################"
exit 0
fi

command="ls -la"

if [[ "$1" == "-so" || "$1" == "-s" ]]
then
        echo "Fired command:"
        echo "$command"
fi

if [[ "$1" != "-so" ]]
then
        $command
fi

现在执行./prova.sh -h就只会输出帮助信息,完全符合预期。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 09:54:21