bash - 检查未传递的参数时出现意外标记 `fi' 附近的语法错误

标签 bash shell

我是 shell 脚本的新手,并创建了一个脚本来检查参数是否已传递或未使用 if else 条件。但它总是给出错误 'syntax error near unexpected token `fi' '

是否总是需要在 if 条件括号后使用 ';'
我在 http://www.compileonline.com/execute_bash_online.php 上在线运行它它运行良好但不适用于我的系统(Centos 6.2)。我是在环境设置中遗漏了什么还是其他什么。

代码

#!/bin/bash
echo "print a message"
if [ $# -eq 1 ]; then
    echo "Argument are passed to shell script"
else
    echo "No arguments are passed to shell script"
fi

错误信息

[root@local shell_scripts]# sh test.sh 12 13
test.sh: line 7: syntax error near unexpected token `fi'
test.sh: line 7: `fi'
[root@local shell_scripts]#

我的环境详情

[root@local shell_scripts]# env
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
SSH_CLIENT=192.168.1.17 49656 22
PERL5LIB=/home/bharat/perl5/lib/perl5/x86_64-linux-thread-multi:/home/bharat/perl5/lib/perl5
PERL_MB_OPT=--install_base /home/bharat/perl5
SSH_TTY=/dev/pts/6
USER=bharat
PATH=/home/bharat/perl5/bin:/usr/kerberos/sbin:/home/bharat/perl5/bin:/usr/kerberos/bin:/usr/local/bin:/bin:/usr/bin:/home/bharat/bin
MAIL=/var/spool/mail/bharat
INPUTRC=/etc/inputrc
LANG=en_US.UTF-8
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
HOME=/root
SHLVL=4
PERL_LOCAL_LIB_ROOT=/home/bharat/perl5
LOGNAME=bharat
CVS_RSH=ssh
LESSOPEN=|/usr/bin/lesspipe.sh %s
G_BROKEN_FILENAMES=1
PERL_MM_OPT=INSTALL_BASE=/home/bharat/perl5
_=/bin/env
[root@local shell_scripts]#

最佳答案

回答您的第一个问题:在 if 条件之后不需要 ;。从句法上讲,then 应该放在单独的一行中。如果 then 在第一行,则使用 ;。以下代码是正确的:

if [ $# -eq 1 ]
then
    echo ok
fi

此外,这些括号实际上并不是 if 条件括号。如果条件是任何有效的 bash 命令,并且括号等同于 test,请参阅 man test 以获取引用。

以下是有效的 if 语句开头:

if cp a.txt b.txt ; then ...
if test $# -eq 1 ; then ...

第二个等同于您的 if 语句。

关于bash - 检查未传递的参数时出现意外标记 `fi' 附近的语法错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18822933/

相关文章:

bash - 如何在bash中删除多个匹配项

linux - 在没有父进程终止的情况下处理 SIGHUP 信号并将其传播到子进程

c - 构建执行作为参数传递的程序的简单 shell 脚本

xml - Unix 中的脚本从文件中删除 XML 标签和内容

shell - < 生成子 shell 时的文档在哪里

linux - bash 中的安全递归删除

linux - 使用 LINUX top 命令计算已用内存百分比

bash - 每个字单独一行

c - 如果我无权访问文件,如何在 shell 中打开该文件?

bash - scp 在复制大文件时停止