击:如何做一个算术前pression内的变量扩展? [英] Bash: How to do a variable expansion within an arithmetic expression?

查看:89
本文介绍了击:如何做一个算术前pression内的变量扩展?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在试图写一个简单的bash脚本来帮助
我的部署过程中,我跑了一个令人困惑的错误:

While attempting to write a simple bash script to help with my deployment process, I ran in to a confusing error:

#!/bin/bash
WEEKDAY=$(date +'%u')
echo $WEEKDAY
DAYS_TO_WEDNESDAY=$((3-$WEEKDAY))
echo $DAYS_TO_WEDNESDAY

结果:

1
")syntax error: invalid arithmetic operator (error token is "

它的奇怪的是,我可以发誓,这
非常脚本运行得很好前几天。

The strangest part of it is that I could swear that this very script ran perfectly well some days ago.

这个问题是不是与bash脚本,而是通过TortoiseSVN的使用SVN。通过Windows的弯路改变EOL标志为CR LF,这导致在bash语法错误。设置SVN:EOL风格 - 属性有助于避免进一步的类似问题。

The issue was not with the bash script, but with using SVN through TortoiseSVN. The detour through Windows changed EOL markers to "CR LF", which result in syntax errors in bash. Setting svn:eol-style -property helps avoid further similar issues.

推荐答案

您的错误信息似乎表明你的数据与污染的CR。

Your error message seems to indicate pollution of your data with CRs.

")syntax error: invalid arithmetic operator (error token is "

请注意,是应该出现在你行的当前结束后的东东是如何开头。这很可能是因为您的错误标记,其实是CR(这是一个回车符 - 即指示终端把光标放在行的开头的字符)。这些字符几乎仅用于Windows机器,他们是行结尾的一部分。

Notice how the stuff that's supposed to come after the current end of your line is at the beginning. That's most likely because your error token is in fact a CR (which is a carriage return character - a character that instructs the terminal to put the cursor on the beginning of the line). These characters are almost only used by Windows machines where they are part of line endings.

我会假设你是Windows机器上,以及你的工作date命令给输出后跟一个窗口换行,这实际上是一个\\ r \\ n(回车符,换行符)。在$()总是尾随去除换行,它离开\\ r结尾导致你的脚本解析问题。

I will assume that you're working on a windows machine and that your "date" command gave the output followed by a "windows" newline, which is actually a \r\n (carriage return, newline). The $() always strips trailing newlines, which leaves the \r at the end causing parsing problems in your script.

下面,下面的命令会产生在UNIX上的错误:

Here, the following command produces your error on UNIX:

$ foo=$'5\r'; echo $((5+foo))
")syntax error: invalid arithmetic operator (error token is "

要解决这个问题,你需要在你的数据摆脱\\ r的。您可以使用此参数扩展,或TR(1)。

To resolve the issue, you need to get rid of the \r in your data. You can use parameter expansion for this, or tr(1).

$ foo=$'5\r'; echo $((5+${foo//$'\r'}))
10

$ $ foo=$'5\r'; echo $((5+$(tr -d '\r' <<< "$foo")))
10

这篇关于击:如何做一个算术前pression内的变量扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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