【问题标题】:Bash Script- Issue with variables and | bcBash 脚本- 变量问题和 |公元前
【发布时间】:2018-05-05 19:41:52
【问题描述】:

所以我有一个变量,我想与 if 语句中的另一个数字进行比较。

b=8.25
if [ $(echo "$b < 10" | bc) -ne 0 ]; then
echo "hey"
fi

我收到以下错误

(standard_in) 1: syntax error

我知道问题在于里面有 b 变量,我怎样才能让它在那里我可以维护它?

请帮忙

【问题讨论】:

  • 它在 Bash 中对我有用。你用的是什么外壳?
  • 你可以试试 b=$'8.25\r';[ ${b%.*} -lt 10 ] && echo "hey"

标签: bash bc


【解决方案1】:

您的脚本文件可能有 DOS 样式的 CRLF 行结尾:

$ b=8.25
$ if [ $(echo "$b < 10" | bc) -ne 0 ]; then
> echo "hey"
> fi
hey

$ b=$'8.25\r'
$ if [ $(echo "$b < 10" | bc) -ne 0 ]; then
> echo "hey"
> fi
(standard_in) 1: illegal character: ^M
bash: [: -ne: unary operator expected

在你的脚本文件上运行dos2unix

【讨论】:

  • 我在学校使用 mobaXterm,但没有运行 dos2unix 的权限,我还能做什么?
  • 这两个事实彼此无关。使用sed 's/\r$//'
【解决方案2】:

将比较结果存储在一个变量中

b=8.25

# Capture output outside the if
comparison=$(echo  "$b < 10" | bc)

# Use the output in the if
if [ $comparison -ne 0 ]; then

    echo "hey"
fi

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多