首页 > 解决方案 > bash 脚本导致意外标记附近出现语法错误

问题描述

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

这是我的bash代码:

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

# Detecting Command Line Arguments
if [ "$1" != "" ]; then
    # check if the screen argument exist
    if ! screen -list | grep -q "$1"; then
        # create screen with new argument
        screen -S $1
    # At this point, argument is not found on screen
    else
        # Create it with argument specified.
        screen -x $1
# 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 ]]好不了多少。

有人有想法吗?

标签: bashgnu-screen

解决方案


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

以下是该网站提供的结果:

$ shellcheck myscript

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

Line 10:
    if ! screen -list | grep -q "$1"; 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.

$

推荐阅读