Bash 中的 if、elif、else 语句问题 [英] if, elif, else statement issues in Bash

查看:45
本文介绍了Bash 中的 if、elif、else 语句问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我似乎无法弄清楚与 elifthen 相关的以下 if 语句的问题是什么.请记住,printf 仍在开发中,我只是无法在语句中对其进行测试,因此很可能是错误的.

I can't seem to work out what the issue with the following if statement is in regards to the elif and then. Keep in mind the printf is still under development I just haven't been able to test it yet in the statement so is more than likely wrong.

我得到的错误是:

./timezone_string.sh: line 14: syntax error near unexpected token `then'
./timezone_string.sh: line 14: `then'

声明是这样的.

if [ "$seconds" -eq 0 ];then
   $timezone_string="Z"
elif[ "$seconds" -gt 0 ]
then
   $timezone_string=`printf "%02d:%02d" $seconds/3600 ($seconds/60)%60`
else
   echo "Unknown parameter"
fi

推荐答案

elif[ 之间缺少空格:

There is a space missing between elif and [:

elif[ "$seconds" -gt 0 ]

应该是

elif [ "$seconds" -gt 0 ]

总而言之,要遵循的语法是:

All together, the syntax to follow is:

if [ conditions ]; then
   # Things
elif [ other_conditions ]; then
   # Other things
else
   # In case none of the above occurs
fi


当我看到这个问题获得了很多观点时,重要的是指出要遵循的语法是:


As I see this question is getting a lot of views, it is important to indicate that the syntax to follow is:

if [ conditions ]
# ^ ^          ^

意味着括号周围需要空格.否则,它不会工作.这是因为 [ 本身一个命令.

meaning that spaces are needed around the brackets. Otherwise, it won't work. This is because [ itself is a command.

您没有看到类似 elif[: command not found(或类似内容)的原因是在看到 ifthen 之后,shell 正在寻找 elifelsefi.然而,它找到了另一个 then(在格式错误的 elif[ 之后).只有解析语句后,它才会被执行(并且会输出类似elif[: command not found的错误信息).

The reason why you are not seeing something like elif[: command not found (or similar) is that after seeing if and then, the shell is looking for either elif, else, or fi. However it finds another then (after the mis-formatted elif[). Only after having parsed the statement it would be executed (and an error message like elif[: command not found would be output).

这篇关于Bash 中的 if、elif、else 语句问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆