Bash if then else语法 [英] Bash if then else syntax

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

问题描述

我正在尝试使用if then else语句使用bash脚本进行测试自动化,但是遇到了一些错误.例如,当我尝试执行它时,使用j和k进行变量赋值时出现了问题,因为它告诉我在尝试执行时找不到命令j和命令k.您如何正确创建变量? 不过,最令人困惑的是,当我尝试执行脚本时,出现一个错误,告诉我在fi附近有一个意外的令牌,然后它只是说'fi'.我在这里做什么错了?

I'm trying to do test automation with a bash script using if then else statements but I'm running into a few errors. For one, when I try to execute it I'm doing something wrong with the variable assignment with j and k, because it tells me that the command j and the command k aren't found when I try to execute. How do you correctly create variables? The most confusing thing though is when I try to execute the script I get an error telling me I have an unexpected token near fi, and then it just says 'fi'. What am I doing wrong here?

#!/bin/bash

j = 0
k = 0

echo Test1:
echo -ne "0\nIn\nUG\n" | /u/cgi_web/Tuition/cost
echo Test2:
echo -ne "0\nOut\nUG\n" | /u/cgi_web/Tuition/cost
echo Test3:
echo -ne "0\nIn\nGR\n" | /u/cgi_web/Tuition/cost
echo Test4:
echo -ne "0\nOut\nGR\n" | /u/cgi_web/Tuition/cost

for i in {1..17}
do
    echo Test$((i+4)):
if[ "$j" -eq 0 ] && [ "$k" -eq 0 ] then
    $j = 1
    echo -ne "$i\nIn\nUG\n" | /u/cgi_web/Tuition/cost
elif[ "$j" -eq 1 ] && [ "$k" -eq 0 ] then
    $k = 1
    echo -ne "$i\nIn\nGR\n" | /u/cgi_web/Tuition/cost
elif[ "$j" -eq 1 ] && [ "$k" -eq 1 ] then
    $j = 0
    echo -ne "$i\nOut\nUG\n" | /u/cgi_web/Tuition/cost
elif[ "$j" -eq 0 ] && [ "$k" -eq 1 ] then
    $k = 0
    echo -ne "$i\nOut\nGR\n" | /u/cgi_web/Tuition/cost
fi

done

我想出了j和k的变量问题,我不得不删除语句中的空格.

I figure out the variable issue with j and k, I had to remove the spaces in the statement.

推荐答案

为帮助将来可能会寻求帮助的任何人,我认为我会回答自己的问题,并从中发现所有的语法错误测试以及他人的有益回应. 要开始变量分配:

To help anyone who might look at this for help in the future, I figured I'd answer my own question with all the syntax errors I found from my own testing and with the helpful responses of others. To start the variable assignment:

j = 0

您之间不能有空格,所以应该是:

you can't have spaces in between, so it would be:

j=0

另外,if语句在if和方括号之间需要一个空格,并且在此之前的最后一个方括号之后需要一个分号.因此,我的不正确的if语句

Also if statements need a space between if and the bracket and need a semicolon after the last bracket before then. Therefore my incorrect if statement

if[ "$j" -eq 0 ] && [ "$k" -eq 0 ] then

成为

if [ "$j" -eq 0 ] && [ "$k" -eq 0 ]; then

或者代替分号,您可以在方括号之间添加新行,这样它将变成

or instead of a semicolon you can have a new line between the bracket, so it would become

if [ "$j" -eq 0 ] && [ "$k" -eq 0 ]
then

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

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