bash 脚本结果出现意外标记附近的语法错误

bash script result a syntax error near unexpected token

我正在尝试编写我的 SCREEN 访问脚本并尽可能自动化我与我的堡垒主机的连接。

这里是我的 bash 代码:

#!/bin/bash
# set TERM to xterm-256color
export TERM=xterm-256color
# here we source bashrc
. .bashrc

# Detecting Command Line Arguments
if [ "" != "" ]; then
    # check if the screen argument exist
    if ! screen -list | grep -q ""; then
        # create screen with new argument
        screen -S 
    # At this point, argument is not found on screen
    else
        # Create it with argument specified.
        screen -x 
# Detecting if default screen exist
elif [[ ! screen -list | grep -q "myscreen" ]]; then
    # no default screen exist, Create it !
    screen -S myscreen
else
    # attache to the default screen
    screen -x myscreen
fi

有输出:

$ ./myscreen.sh test123
./myscreen.sh: line 18: syntax error near unexpected token `elif'
./myscreen.sh: line 18: `elif ! screen -list | grep -q "myscreen" ; then'

我也试过 [[ ! EXPR ]] 好不了多少。

有人有想法吗?

您缺少用于关闭内部 if-else 的 fi 语句:

if 
    if 
        ...
    else 
        ...
    fi  # You were missing this line
elif 
    ...
else
    ...
fi

我查看了您的脚本,发现它在 elif 之前缺少一个 fi。当然,我每天都写 bash 代码,所以我很容易发现这一点。您可以使用 bash 语法检查器来帮助检查您的脚本 (www.shellcheck.net)。

这是该站点提供的结果:

$ shellcheck myscript

Line 8:
if [ "" != "" ]; then
                   ^-- SC1009: The mentioned syntax error was in this then clause.

Line 10:
    if ! screen -list | grep -q ""; then
    ^-- SC1046: Couldn't find 'fi' for this 'if'.
    ^-- SC1073: Couldn't parse this if expression. Fix to allow more checks.

Line 18:
elif [[ ! screen -list | grep -q "myscreen" ]]; then
^-- SC1047: Expected 'fi' matching previously mentioned 'if'.
     ^-- SC1072: Unexpected keyword/token. Fix any mentioned problems and try again.

$