Integer expression expected ошибка bash

I'm a newbie to shell scripts so I have a question. What Im doing wrong in this code? #!/bin/bash echo " Write in your age: " read age if [ "$age" -le "7"] -o [ "$age" -ge " 65" ] then echo " You ...

I’m a newbie to shell scripts so I have a question. What Im doing wrong in this code?

#!/bin/bash
echo " Write in your age: "
read age
if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
then
echo " You can walk in for free "
elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
then
echo " You have to pay for ticket "
fi

When I’m trying to open this script it asks me for my age and then it says

./bilet.sh: line 6: [: 7]: integer expression expected
./bilet.sh: line 9: [: missing `]'

I don’t have any idea what I’m doing wrong. If someone could tell me how to fix it I would be thankful, sorry for my poor English I hope you guys can understand me.

chepner's user avatar

chepner

478k70 gold badges502 silver badges652 bronze badges

asked Oct 21, 2013 at 21:36

user2904832's user avatar

3

You can use this syntax:

#!/bin/bash

echo " Write in your age: "
read age

if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
    echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
    echo " You have to pay for ticket "
fi

answered Oct 21, 2013 at 21:43

kamituel's user avatar

kamituelkamituel

33.9k5 gold badges80 silver badges98 bronze badges

2

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel’s answer. The above will work in any POSIX-compliant shell.

Community's user avatar

answered Oct 21, 2013 at 21:45

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges652 bronze badges

1

This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.

For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "n" or "r".

For example:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

This will result in a script error : integer expression expected because $a contains a non-digit newline character "n". You have to remove this character using the instructions here: How to remove carriage return from a string in Bash

So use something like this:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'trn ']}"

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

You can also use set -xv to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/

answered Feb 9, 2018 at 11:56

Mr-IDE's user avatar

Mr-IDEMr-IDE

6,6051 gold badge51 silver badges58 bronze badges

1

./bilet.sh: line 6: [: 7]: integer expression expected

Be careful with " "

./bilet.sh: line 9: [: missing `]'

This is because you need to have space between brackets like:

if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]

look: added space, and no " "

Dan Lowe's user avatar

Dan Lowe

49k18 gold badges122 silver badges111 bronze badges

answered May 11, 2017 at 14:28

circassia_ai's user avatar

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then n
     Something something n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then n
     Something something n
else n
    Yes it works for me :) n

Juan Serrats's user avatar

Juan Serrats

1,3585 gold badges24 silver badges30 bronze badges

answered Jul 10, 2017 at 8:24

Harry1992's user avatar

Harry1992Harry1992

4551 gold badge5 silver badges12 bronze badges

1

If you are just comparing numbers, I think there’s no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ «$age» -le «7»] -o [ «$age» -ge » 65″ ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ «$age» -gt «7»] -a [ «$age» -lt «65»]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

answered Apr 27, 2020 at 16:37

markfree's user avatar

By the look of things, your result variable has a . in it after the number making bash not recognise it as such. You can reproduce the error by simply doing:

[ 7. -gt 1 ]

If you add more of the script to your question, |I can suggest where this might be coming from.

Update

Looking at the full script, I would just replace the line:

result=$(echo "$used / $total * 100" |bc -l|cut -c -2)

With:

result=$(( 100 * used / total ))

Since used and total are integers and bash does integer arithmetic, though note the shifting of the multiplication be 100 to the beginning. Or if you want to ensure correct rounding (‘integer division’ in computing always effectively rounds down):

result=$( printf '%.0f' $(echo "$used / $total * 100" | bc -l) )

This will ensure that there are no trailing dots in result. The approach using cut is not a very good idea since it is only valid for result in the range 10-99. It will fail for a result from 0-9 (as in your case) and also numbers above 99.

Update 2

From @Stephane’s comment below, you are better to round down when comparing to thresholds. Considering this, there is another small error with the snippet in the question — notice the inconsistency between the comparisons used for the warn_level and the critical_level. The comparisons for warn_level are correct, but critical_level uses -le (lesser or equal) instead of -lt (just lesser). Consider when result is slightly larger than critical_level — it will be rounded down to critical_level and not trigger the critical warning even though it should (and would if a -lt comparison was used).

Perhaps not much of an issue, but here is the corrected code:

if [ "$result" -lt "$warn_level" ]; then
  echo "Memory OK. $result% used."
  exit 0;
elif [ "$result" -lt "$critical_level" ]; then
  echo "Memory WARNING. $result% used."
  exit 1;
else
  echo "Memory CRITICAL. $result% used."
  exit 2;
fi

The -ge tests are also redundant since these cases are implied on reaching the elif/else, so have been removed.

����� 31. ������ ���������������� ������

Turandot: Gli enigmi sono tre, la morte
una!

Caleph: No, no! Gli enigmi sono tre, una la
vita!

Puccini

������������� ����������������� ���� � ��������� �������� �
�������� ���� ����������.

case=value0       # ����� ������� ��������.
23skidoo=value1   # ���� �����.
# ����� ����������, ������������ � ����, ��������������� ��������� ���������.
# ���� ��� ���������� ���������� � ������� �������������: _23skidoo=value1, �� ��� �� ��������� �������.

# ������... ���� ��� ���������� ������� �� ������������� ������� �������������, �� ��� ������.
_=25
echo $_           # $_  -- ��� ���������� ����������.

xyz((!*=value2    # �������� ��������� ��������.

������������� ������, � ������ ����������������� ��������, �
������ ����������.

var-1=23
# ������ ����� ������ ����������� 'var_1'.

������������� ���������� ���� ��� ���������� � �������. ���
������ �������� ������� ��� ���������.

do_something ()
{
  echo "��� ������� ������ ���-������ ������� � "$1"."
}

do_something=do_something

do_something do_something

# ��� ��� ����� �������� ���������, �� ������� �� ���������.

������������� ������ ��������. � ������� �� ������
������ ����������������, Bash ������ ����������� �� ��������� �
��������.

var1 = 23   # ���������� �������: 'var1=23'.
# � ��������������� ������ Bash ����� ���������� "var1" ��� ��� �������
# � ����������� "=" � "23".

let c = $a - $b   # ���������� �������: 'let c=$a-$b' ��� 'let "c = $a - $b"'

if [ $a -le 5]    # ���������� �������: if [ $a -le 5 ]
# if [ "$a" -le 5 ]   ��� �����.
# [[ $a -le 5 ]] ���� �����.

��������� �������� ������������� � ���, ���
�������������������� ���������� �������� «����». ��������������������
���������� �������� «������» (null) ��������, � �� ����.

#!/bin/bash

echo "uninitialized_var = $uninitialized_var"
# uninitialized_var =

����� ������������ ������ ��������� ��������� =-eq. ���������, �������� = ������������ ��� ���������
��������� ����������, � -eq — ��� ��������� �����
�����.

if [ "$a" = 273 ]      # ��� �� ���������? $a -- ��� ����� ����� ��� ������?
if [ "$a" -eq 273 ]    # ���� $a -- ����� �����.

# ������, ������ ���� ������ ����� ���� �� ���������.
# ������...


a=273.0   # �� ����� �����.

if [ "$a" = 273 ]
then
  echo "�����."
else
  echo "�� �����."
fi    # �� �����.

# ���� ����� � ���  a=" 273"  �  a="0273".


# �������� �������� ��������� ��� ������������� "-eq" �� ���������� ����������.

if [ "$a" -eq 273.0 ]
then
  echo "a = $a'
fi  # ���������� �������� ����������� �� ������.
# test.sh: [: 273.0: integer expression expected

������ ��� ��������� ����� ����� � ��������� ��������.

#!/bin/bash
# bad-op.sh

number=1

while [ "$number" < 5 ]    # �������! ������ ����   while [ "number" -lt 5 ]
do
  echo -n "$number "
  let "number += 1"
done

# ���� �������� ���������� ��������� �� ������:
# bad-op.sh: 5: No such file or directory

������, � ��������� ��������, � �������������� ����������
������ ([ ]), ���������� ���������� ����� � ������� �������. ��.
������ 7-6, ������ 16-4 � ������ 9-6.

������ �������� �� � ��������� ��������� ������� ��-��
�������� ���� �������. ���� ������������ �� ������ ���������
������� �� ��������� ������, �� ��� ������� �� ������ ����
�������� � �� ��������. ���������� �������� �������� �������,
�������� ��� �������� ���������� ��� suid.

������������� ������� � �������� ��������� ���������������
(������� �� �� ��������) ����� ��������� � �����������
�����������.

command1 2> - | command2  # ������� �������� ��������� �� ������� ������� command1 ����� ��������...
#    ...�� ����� ��������.

command1 2>& - | command2  # ��� �� ������������.

������� S.C.

������������� �������������� ������������ Bash ������ 2 ��� ����, �����
�������� � ���������� ���������� ��������, ����������� ���
����������� Bash ������ 1.XX.

#!/bin/bash

minimum_version=2
# ��������� Chet Ramey ��������� ��������� Bash,
# ��� ����� ������������� ������� ������ ���������� ���������� ������ $minimum_version=2.XX.
E_BAD_VERSION=80

if [ "$BASH_VERSION" < "$minimum_version" ]
then
  echo "���� �������� ������ ����������� ��� ����������� Bash, ������ $minimum ��� ����."
  echo "������������ ������������� ����������."
  exit $E_BAD_VERSION
fi

...

������������� ������������� ������������ Bash ����� ���������
� ���������� ���������� �������� � Bourne shell (#!/bin/sh). ��� �������,
� Linux �������������, sh �������� ����������� bash, �� ��� �� ������ ����� ���
UNIX-������ ������.

��������, � ������� ������ ���������� ���� �� ����� � �����
MS-DOS (rn), ����� �����������
��������, ��������� ���������� #!/bin/bashrn
��������� ������������. ��������� ��� ������ ����� �������
��������� ������� r �� ��������.

#!/bin/bash

echo "������"

unix2dos $0    # �������� ��������� ������� �������� ������ � ������ DOS.
chmod 755 $0   # �������������� ���� �� ������.
               # ������� 'unix2dos' ������ ����� �� ������ �� ��������� �����.

./$0           # ������� ��������� ���� ������.
               # �� ��� �� ��������� ��-�� ����, ��� ������ ������ ����������
               # ���� �� ����� � ����� DOS.

echo "�����"

exit 0

��������, ������������ � #!/bin/sh, �� �����
�������� � ������ ������ ������������� � Bash. ��������� ��
������������� �������, �������� Bash, ����� ���������
������������ � �������������. ��������, ������� ������� �������
������� �� ���� �����������, ��������� � Bash, ������ ����������
������� #!/bin/bash.

�������� �� ����� �������������� ���������� ������������� �������� — ��������.
����� ��� � �������, ������� ����� ������������ ����� ��������,
�� �� ���������.

WHATEVER=/home/bozo
export WHATEVER
exit 0
bash$ echo $WHATEVER

bash$

������ ������� — ��� ������ � ��������� ������ ����������
$WHATEVER ��������� ��������������������.

������������� � ����������� ���������� � ���� �� �������, ���
� � ������������ �������� ����� �� ������ ����������
����������.

������ 31-1. ������� � �����������

#!/bin/bash
# ������� � �����������.

outer_variable=�������_����������
echo
echo "outer_variable = $outer_variable"
echo

(
# ������ � �����������

echo "������ ����������� outer_variable = $outer_variable"
inner_variable=����������_����������  # ����������������
echo "������ ����������� inner_variable = $inner_variable"
outer_variable=����������_����������  # ��� �������? ������� ������� ����������?
echo "������ ����������� outer_variable = $outer_variable"

# ����� �� �����������
)

echo
echo "�� ��������� ����������� inner_variable = $inner_variable"  # ������ �� ���������.
echo "�� ��������� ����������� outer_variable = $outer_variable"  # �������_����������.
echo

exit 0

�������� ������ �� echo �� ��������� ������� read ����� ������ �����������
����������. � ���� ��������, ������� read ��������� ���, ��� ����� �� ���
���� �������� � �����������. ������ ��� ����� ������������
������� set (��. ������ 11-14).

������ 31-2. �������� ������ �� ������� echo �������
read, �� ���������

#!/bin/bash
#  badread.sh:
#  ������� ������������� 'echo' � 'read'
#+ ��� ������ �������� � ����������.

a=aaa
b=bbb
c=ccc

echo "���� ��� ���" | read a b c
# ������� �������� �������� � ���������� a, b � c.

echo
echo "a = $a"  # a = aaa
echo "b = $b"  # b = bbb
echo "c = $c"  # c = ccc
# ������������ �� ���������.

# ------------------------------

# �������������� �������.

var=`echo "���� ��� ���"`
set -- $var
a=$1; b=$2; c=$3

echo "-------"
echo "a = $a"  # a = ����
echo "b = $b"  # b = ���
echo "c = $c"  # c = ���
# �� ���� ��� ��� � �������.

# ------------------------------

#  �������� ��������: � ����������� 'read', ��� ������� ��������, ���������� ������������� ���������.
#  �� ������ � �����������.

a=aaa          # ��� �������.
b=bbb
c=ccc

echo; echo
echo "���� ��� ���" | ( read a b c;
echo "������ �����������: "; echo "a = $a"; echo "b = $b"; echo "c = $c" )
# a = ����
# b = ���
# c = ���
echo "-------"
echo "�������: "
echo "a = $a"  # a = aaa
echo "b = $b"  # b = bbb
echo "c = $c"  # c = ccc
echo

exit 0

�������� ����, ��� ������������ �������, ������������
������������� � �������� ������, � ������������� ����� «suid». [1]

������������� ��������� � �������� CGI-���������� �����
��������� � ��������� ��������� ��-�� ���������� �������� �����
����������. ����� ����, ��� ����� ����� ���� �������� ����������
�� ��� ����������� ��������.

Bash �� ������ ��������� ������������ ������, ���������� ������� ���� (//).

�������� �� ����� Bash, ��������� ��� Linux ��� BSD ������,
����� ����������� ���������, ����� ��� ��� ��� ������ ����
�������� � ������������ ������ UNIX. ����� ��������, ��� �������,
���������� GNU-������ ������ � ������, ������� ����� ������
����������������, ������ �� ������� � UNIX. ��� ��������
����������� ��� ����� ������ ��������� ������, ��� tr.

Danger is near thee —

Beware, beware, beware, beware.

Many brave hearts are asleep in the deep.

So beware —

Beware.

A.J. Lamb and H.W.
Petrie

I’m a newbie to shell scripts so I have a question. What Im doing wrong in this code?

#!/bin/bash
echo " Write in your age: "
read age
if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
then
echo " You can walk in for free "
elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
then
echo " You have to pay for ticket "
fi

When I’m trying to open this script it asks me for my age and then it says

./bilet.sh: line 6: [: 7]: integer expression expected
./bilet.sh: line 9: [: missing `]'

I don’t have any idea what I’m doing wrong. If someone could tell me how to fix it I would be thankful, sorry for my poor English I hope you guys can understand me.

chepner's user avatar

chepner

478k70 gold badges502 silver badges652 bronze badges

asked Oct 21, 2013 at 21:36

user2904832's user avatar

3

You can use this syntax:

#!/bin/bash

echo " Write in your age: "
read age

if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
    echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
    echo " You have to pay for ticket "
fi

answered Oct 21, 2013 at 21:43

kamituel's user avatar

kamituelkamituel

33.9k5 gold badges80 silver badges98 bronze badges

2

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel’s answer. The above will work in any POSIX-compliant shell.

Community's user avatar

answered Oct 21, 2013 at 21:45

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges652 bronze badges

1

This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.

For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "n" or "r".

For example:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

This will result in a script error : integer expression expected because $a contains a non-digit newline character "n". You have to remove this character using the instructions here: How to remove carriage return from a string in Bash

So use something like this:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'trn ']}"

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

You can also use set -xv to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/

answered Feb 9, 2018 at 11:56

Mr-IDE's user avatar

Mr-IDEMr-IDE

6,6051 gold badge51 silver badges58 bronze badges

1

./bilet.sh: line 6: [: 7]: integer expression expected

Be careful with " "

./bilet.sh: line 9: [: missing `]'

This is because you need to have space between brackets like:

if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]

look: added space, and no " "

Dan Lowe's user avatar

Dan Lowe

49k18 gold badges122 silver badges111 bronze badges

answered May 11, 2017 at 14:28

circassia_ai's user avatar

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then n
     Something something n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then n
     Something something n
else n
    Yes it works for me :) n

Juan Serrats's user avatar

Juan Serrats

1,3585 gold badges24 silver badges30 bronze badges

answered Jul 10, 2017 at 8:24

Harry1992's user avatar

Harry1992Harry1992

4551 gold badge5 silver badges12 bronze badges

1

If you are just comparing numbers, I think there’s no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ «$age» -le «7»] -o [ «$age» -ge » 65″ ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ «$age» -gt «7»] -a [ «$age» -lt «65»]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

answered Apr 27, 2020 at 16:37

markfree's user avatar

I’m a newbie to shell scripts so I have a question. What Im doing wrong in this code?

#!/bin/bash
echo " Write in your age: "
read age
if [ "$age" -le "7"] -o [ "$age" -ge " 65" ]
then
echo " You can walk in for free "
elif [ "$age" -gt "7"] -a [ "$age" -lt "65"]
then
echo " You have to pay for ticket "
fi

When I’m trying to open this script it asks me for my age and then it says

./bilet.sh: line 6: [: 7]: integer expression expected
./bilet.sh: line 9: [: missing `]'

I don’t have any idea what I’m doing wrong. If someone could tell me how to fix it I would be thankful, sorry for my poor English I hope you guys can understand me.

chepner's user avatar

chepner

478k70 gold badges502 silver badges652 bronze badges

asked Oct 21, 2013 at 21:36

user2904832's user avatar

3

You can use this syntax:

#!/bin/bash

echo " Write in your age: "
read age

if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
    echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
    echo " You have to pay for ticket "
fi

answered Oct 21, 2013 at 21:43

kamituel's user avatar

kamituelkamituel

33.9k5 gold badges80 silver badges98 bronze badges

2

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel’s answer. The above will work in any POSIX-compliant shell.

Community's user avatar

answered Oct 21, 2013 at 21:45

chepner's user avatar

chepnerchepner

478k70 gold badges502 silver badges652 bronze badges

1

This error can also happen if the variable you are comparing has hidden characters that are not numbers/digits.

For example, if you are retrieving an integer from a third-party script, you must ensure that the returned string does not contain hidden characters, like "n" or "r".

For example:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

This will result in a script error : integer expression expected because $a contains a non-digit newline character "n". You have to remove this character using the instructions here: How to remove carriage return from a string in Bash

So use something like this:

#!/bin/bash

# Simulate an invalid number string returned
# from a script, which is "1234n"
a='1234
'

# Remove all new line, carriage return, tab characters
# from the string, to allow integer comparison
a="${a//[$'trn ']}"

if [ "$a" -gt 1233 ] ; then
    echo "number is bigger"
else
    echo "number is smaller"
fi

You can also use set -xv to debug your bash script and reveal these hidden characters. See https://www.linuxquestions.org/questions/linux-newbie-8/bash-script-error-integer-expression-expected-934465/

answered Feb 9, 2018 at 11:56

Mr-IDE's user avatar

Mr-IDEMr-IDE

6,6051 gold badge51 silver badges58 bronze badges

1

./bilet.sh: line 6: [: 7]: integer expression expected

Be careful with " "

./bilet.sh: line 9: [: missing `]'

This is because you need to have space between brackets like:

if [ "$age" -le 7 ] -o [ "$age" -ge 65 ]

look: added space, and no " "

Dan Lowe's user avatar

Dan Lowe

49k18 gold badges122 silver badges111 bronze badges

answered May 11, 2017 at 14:28

circassia_ai's user avatar

Try this:

If [ $a -lt 4 ] || [ $a -gt 64 ] ; then n
     Something something n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then n
     Something something n
else n
    Yes it works for me :) n

Juan Serrats's user avatar

Juan Serrats

1,3585 gold badges24 silver badges30 bronze badges

answered Jul 10, 2017 at 8:24

Harry1992's user avatar

Harry1992Harry1992

4551 gold badge5 silver badges12 bronze badges

1

If you are just comparing numbers, I think there’s no need to change syntax, just correct those lines, lines 6 and 9 brackets.

Line 6 before: if [ «$age» -le «7»] -o [ «$age» -ge » 65″ ]

After: if [ "$age" -le "7" -o "$age" -ge "65" ]

Line 9 before: elif [ «$age» -gt «7»] -a [ «$age» -lt «65»]

After: elif [ "$age" -gt "7" -a "$age" -lt "65" ]

answered Apr 27, 2020 at 16:37

markfree's user avatar

Скрипт выкидывает ошибку: integer expression expected (Конструкция if [ $f -gt 1 -le $f < 99 ]; then использует)

Модератор: Bizdelnick

Аватара пользователя

halo

Сообщения: 128
ОС: debian 4

Скрипт выкидывает ошибку: integer expression expected

Пишу скрипт, который опрашивает удаленный хост. Значение пинга периодически меняется. В зависимости от значения пинга на вебстранице должен меняться фон ячейки таблицы. Красный фон — плохо. Зеленый — хорошо.
Конструкция if [ $f -gt 1 -le $f < 99 ]; then работает только с целочисленными значениями. Соответственно в консоли при запуске скрипта появляется ошибка: integer expression expected

Код:

#!/bin/sh

f=10

while true
do

if [ $f -gt 1 -le $f < 99 ]; then
echo "0 < "f" =< 100"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 100 -a "$f" -le 200 ]; then
echo "* ""100 < "$f" =< 200"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 200 -a "$f" -le 300 ]; then
echo "****""200 < "$f" =< 300"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 300 -a "$f" -le 400 ]; then
echo "******""300 < "$f" =< 400"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
else
echo "********" $f "> 400"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
fi

done

Как побороть этот косяк? Спасибо. :rolleyes:

If I could, I would fly.

Sleeping Daemon

Сообщения: 1450
Контактная информация:

Re: Скрипт выкидывает ошибку: integer expression expected

Сообщение

Sleeping Daemon » 25.07.2009 20:27

halo писал(а): ↑

25.07.2009 19:29

Пишу скрипт, который опрашивает удаленный хост. Значение пинга периодически меняется. В зависимости от значения пинга на вебстранице должен меняться фон ячейки таблицы. Красный фон — плохо. Зеленый — хорошо.
Конструкция if [ $f -gt 1 -le $f < 99 ]; then работает только с целочисленными значениями. Соответственно в консоли при запуске скрипта появляется ошибка: integer expression expected

Код:

#!/bin/sh

f=10

while true
do

if [ $f -gt 1 -le $f < 99 ]; then
echo "0 < "f" =< 100"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 100 -a "$f" -le 200 ]; then
echo "* ""100 < "$f" =< 200"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 200 -a "$f" -le 300 ]; then
echo "****""200 < "$f" =< 300"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
elif [ "$f" -gt 300 -a "$f" -le 400 ]; then
echo "******""300 < "$f" =< 400"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
else
echo "********" $f "> 400"
f=`ping 10.104.199.1 -c 3 | tail -n 1 | awk -F/ '{print $5}'`
fi

done

Как побороть этот косяк? Спасибо. :rolleyes:

Может так? printf(«%in»,$5)

Аватара пользователя

halo

Сообщения: 128
ОС: debian 4

Re: Скрипт выкидывает ошибку: integer expression expected

Сообщение

halo » 25.07.2009 22:45

Спасибо за ответы. Удалите тему!!!

i Уведомление от модератора diesel
темы по просьбам пользователей на этом форуме не удаляют. Хотел написать в личку, но ящик забит. В следующей жалобе потрудитесь объяснить почему вы от нас требуете столь странных действий.

If I could, I would fly.

Introduction

Math and arithmetic operations are essential in Bash scripting. Various automation tasks require basic arithmetic operations, such as converting the CPU temperature to Fahrenheit. Implementing math operations in Bash is simple and very easy to learn.

This guide teaches you how to do basic math in Bash in various ways.

bash math bash arithmetic explained

Prerequisites

  • Access to the command line/terminal.
  • A text editor to code examples, such as nano or Vi/Vim.
  • Basic knowledge of Bash scripting.

Why Do You Need Math in Bash Scripting?

Although math is not the primary purpose of Bash scripting, knowing how to do essential calculations is helpful for various use cases.

Common use cases include:

  • Adding/subtracting/multiplying/dividing numbers.
  • Rounding numbers.
  • Incrementing and decrementing numbers.
  • Converting units.
  • Floating-point calculations.
  • Finding percentages.
  • Working with different number bases (binary, octal, or hexadecimal).

Depending on the automation task, basic math and arithmetic in Bash scripting help perform a quick calculation, yielding immediate results in the desired format.

Bash Math Commands and Methods

Some Linux commands allow performing basic and advanced calculations immediately. This section shows basic math examples with each method.

Arithmetic Expansion

The preferable way to do math in Bash is to use shell arithmetic expansion. The built-in capability evaluates math expressions and returns the result. The syntax for arithmetic expansions is:

$((expression))

The syntax consists of:

  • Compound notation (()) which evaluates the expression.
  • The variable operator $ to store the result.

Note: The square bracket notation ( $[expression] ) also evaluates an arithmetic expression, and should be avoided since it is deprecated.

For example, add two numbers and echo the result:

echo $((2+3))
bash arithmetic expansion addition terminal output

The arithmetic expansion notation is the preferred method when working with Bash scripts. The notation is often seen together with if statements and for loops in Bash.

awk Command

The awk command acts as a selector for pattern expressions. For example, to perform addition using the awk command, use the following example statement:

awk 'BEGIN { x = 2; y = 3; print "x + y = "(x+y) }'
awk addition terminal output

For variables x = 2 and y = 3, the output prints x + y = 5 to the console.

bc Command

The bc command (short for basic calculator) is a command-line utility that renders the bc language. The program runs as an interactive program or takes standard input to perform arbitrary precision arithmetic.

Pipe an equation from standard input into the command to fetch results. For example:

echo "2+3" | bc
bc addition terminal output

The output prints the calculation result.

dc Command

The dc command (short for desk calculator) is a calculator utility that supports reverse Polish notation. The program takes standard input and supports unlimited precision arithmetic.

Pipe a standard input equation into the command to fetch the result. For example:

echo "2 3 + p" | dc
dc addition terminal output

The p in the equation sends the print signal to the dc command.

declare Command

The Bash declare command allows integer calculations. To use declare for calculations, add the -i option. For example:

declare -i x=2 y=3 z=x+y

Echo each variable to see the results:

echo $x + $y = $z
declare addition terminal output

The output prints each variable to the console.

expr Command

The expr command is a legacy command line utility for evaluating integer arithmetic. An example expr command looks like the following:

expr 2 + 3
expr addition terminal output

Separate numbers and the operation sign with spaces and run the command to see the calculation result.

factor Command

The factor command is a command-line utility that prints the factors for any positive integer, and the result factorizes into prime numbers.

For example, to print the factors of the number 100, run:

factor 100
factor 100 terminal output

The output prints the factored number.

let Command

The Bash let command performs various arithmetic, bitwise and logical operations. The built-in command works only with integers. The following example demonstrates the let command syntax:

let x=2+3 | echo $x
let addition terminal output

The output prints the results.

test Command

The test command in Linux evaluates conditional expressions and often pairs with the Bash if statement. There are two variations for the test syntax:

test 2 -gt 3; echo $?
test comparison terminal output

Or alternatively:

[ 2 -gt 3 ]; echo $?
test bracket comparison terminal output

The test command evaluates whether two is greater than (-gt) three. If the expression is true, the output is zero (0), or one (1) if false.

Bash Arithmetic Operators

Bash offers a wide range of arithmetic operators for various calculations and evaluations. The operators work with the let, declare, and arithmetic expansion.

Below is a quick reference table that describes Bash arithmetic operators and their functionality.

Syntax Description
++x, x++ Pre and post-increment.
--x, x-- Pre and post-decrement.
+, -, *, / Addition, subtraction, multiplication, division.
%, ** (or ^) Modulo (remainder) and exponentiation.
&&, ||, ! Logical AND, OR, and negation.
&, |, ^, ~ Bitwise AND, OR, XOR, and negation.
<=, <, >, => Less than or equal to, less than, greater than, and greater than or equal to comparison operators.
==, != Equality and inequality comparison operators.
= Assignment operator. Combines with other arithmetic operators.

How to Do Math in Bash

Bash offers different ways to perform math calculations depending on the type of problem.

Below are examples of some common problems which use Bash math functionalities or commands as a solution. Most examples use the Bash arithmetic expansion notation. The section also covers common Bash math errors and how to resolve them.

Math with Integers

The arithmetic expansion notation is the simplest to use and manipulate with when working with integers. For example, create an expression with variables and calculate the result immediately:

echo $((x=2, y=3, x+y))
bash arithmetic expansion variables terminal output

To evaluate multiple expressions, use compound notation, store each calculation in a variable, and echo the result. For example:

((x=2, y=3, a=x+y, b=x*y, c=x**y)); echo $a, $b, $c
bash multiple equations terminal output

When trying to divide, keep the following in mind:

1. Division by zero (0) is impossible and throws an error.

bash division by zero error terminal output

2. Bash arithmetic expansion does not support floating-point arithmetic. When attempting to divide in this case, the output shows zero (0).

non-integer result terminal output

The result of integer division must be an integer.

Incrementing and Decrementing

Bash arithmetic expansion uses C-style integer incrementing and decrementing. The operator for incrementing or decrementing is either before or after the variable, yielding different behavior.

If the operator is before the variable (++x or --x), the increment or decrement happens before value assignment. To see how pre-incrementing works, run the following lines:

number=1
echo $((++number))
c-style pre-increment terminal output

The variable increments, and the new value is immediately available.

If the operator is after the variable (x++ or x--), the increment or decrement happens after value assignment. To see how post-incrementing works, run the following:

number=1
echo $((number++))
echo $number
c-style post-increment terminal output

The variable stays the same and increments in the following use.

Floating-point Arithmetic

Although Bash arithmetic expansion does not support floating-point arithmetic, there are other ways to perform such calculations. Below are four examples using commands or programming languages available on most Linux systems.

1. Using awk for up to 6 decimal places:

awk 'BEGIN { x = 2.3; y = 3.2; print "x * y = "(x * y) }'
awk bash floating point arithmetic terminal output

2. Using bc with the -l flag for up to 20 decimal places:

echo "2.3 * 3.2" | bc -l
bc -l floating point arithmetic terminal output

3. Using Perl for up to 20 decimal places:

perl -e 'print 2.3*3.2'
perl floating point arithmetic terminal output

Perl often comes preinstalled in Linux systems.

4. Using printf and arithmetic expansion to convert a fraction to a decimal:

printf %.<precision>f "$((10**<multiplier> * <fraction>))e-<multiplier>"

Precision dictates how many decimal places, whereas the multiplier is a power of ten. The number should be lower than the multiplier. Otherwise, the formula puts trailing zeros in the result.

For example, convert 1/3 to a decimal with precision two:

printf %.2f "$((10**3 * 1/3))e-3"
printf bash arithmetic expansion floating point terminal output

Avoid this method for precise calculations and use it only for a small number of decimal places.

Calculating a Percentage and Rounding

Below are two ways to calculate a percentage in Bash.

1. Use printf with arithmetic expansion.

printf %.2f "$((10**4 * part/total))e-4"%

For example, calculate what percent 40 is from 71:

printf %.2f%% "$((10**4 * 40/71))e-4"%
printf percent calculation terminal output

The precision is limited to two decimal places, and the answer always rounds down.

2. Use awk with printf for better precision:

awk 'BEGIN { printf "%.2f%%", (part/total*100) }'

For instance, calculate how many percent is 40 from 71 with:

awk 'BEGIN { printf "%.2f%%", (40/71*100) }'
awk percent calculation terminal output

The answer rounds up if the third decimal place is higher than five, providing better accuracy.

Finding a Factorial in the Shell

To calculate a factorial for any number, use a recursive Bash function.

For small numbers, Bash arithmetic expansion works well:

factorial () { 
    if (($1 > 1))
    then
        echo $(( $( factorial $(($1 - 1)) ) * $1 ))
    else

        echo 1
        return
    fi
}

To check the factorial for a number, use the following syntax:

factorial 5
bash arithmetic expansion factorial function terminal output

The method is slow and has limited precision (up to factorial 20).

For higher precision, faster results, and larger numbers, use the bc command. For example:

echo 'define factorial(x) {if (x>1){return x*factorial(x-1)};return 1}
 factorial(<number>)' | bc

Replace <number> with the factorial number to calculate. For example, to find the factorial of 50, use:

echo 'define factorial(x) {if (x>1){return x*factorial(x-1)};return 1} factorial(50)' | bc
bc factorial function terminal output

The output prints the calculation result to the terminal.

Creating a Bash Calculator Function

Create a simple Bash calculator function with the following code:

calculate() { printf "%sn" "[email protected]" | bc -l; }
calculate bc function terminal output

The function takes user input and pipes the equation into the bc command.

Alternatively, to avoid using programs, use Bash arithmetic expansion in a function:

calculate() { echo $(("[email protected]")); }
calculate bash arithmetic expansion function terminal output

Keep the arithmetic expansion limitations in mind. Floating-point arithmetic is not available with this function.

Save the function into the .bashrc file to always have the function available in the shell.

Using Different Arithmetic Bases

By default, Bash arithmetic expansion uses base ten numbers. To change the number base, use the following format:

base#number

Where base is any integer between two and 64.

For example, to do a binary (base 2) calculation, use:

echo $((2#1010+2#1010))
bash binary math terminal output

Octal (base 8) calculations use a 0 prefix as an alias. For example:

echo $((010+010))
bash octal math terminal output

Hexadecimal (base 16) calculations allow using 0x as a base prefix. For example:

echo $((0xA+0xA))
bash hexadecimal math terminal output

The output prints the result in base ten for any calculation.

Convert Units

Create a simple Bash script to convert units:

1. Open a text editor, such as Vim, and create a convert.sh script. For example:

vim convert.sh

2. Paste the following code:

#!/bin/bash

## Program for feet and inches conversion

echo "Enter a number to be converted:"

read number

echo $number feet to inches:
echo "$number*12" | bc -l

echo $number inches to feet:
echo "$number/12" | bc -l

The program uses Bash read to take user input and calculates the conversion from feet to inches and from inches to feet.

3. Save the script and close:

:wq

4. Run the Bash script with:

. convert.sh
convert.sh bash script terminal output

Enter a number and see the result. For different conversions, use appropriate conversion formulas.

Solving «bash error: value too great for base»

When working with different number bases, stay within the number base limits. For example, binary numbers use 0 and 1 to define numbers:

echo $((2#2+2#2))

Attempting to use 2#2 as a number outputs an error:

bash: 2#2: value too great for base (error token is "2#2")
bash value too great for base error terminal

The number is not the correct format for binary use. To resolve the error, convert the number to binary to perform the calculation correctly:

echo $((2#10+2#10))

The binary number 10 is 2 in base ten.

Solving «syntax error: invalid arithmetic operator»

The Bash arithmetic expansion notation only works for integer calculations. Attempt to add two floating-point numbers, for example:

echo $((2.1+2.1))

The command prints an error:

bash: 2.1+2.1: syntax error: invalid arithmetic operator (error token is ".1+2.1")
bash syntax error invalid arithmetic operator terminal output

To resolve the error, use regular integer arithmetic or a different method to calculate the equation.

Solving «bash error: integer expression expected»

When comparing two numbers, the test command requires integers. For example, try the following command:

[ 1 -gt 1.5 ]

The output prints an error:

bash: [: 1.5: integer expression expected
bash integer expression expected error terminal

Resolve the error by comparing integer values.

Conclusion

You know how to do Bash arithmetic and various calculations through Bash scripting.

For more advanced scientific calculations, use Python together with SciPy, NumPy, and other libraries.

10 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

if condition error: integer expression expected

I am trying to run following condition with both variables having numeric values «1,2,3»

if ;when i run it i get following error:

$NEW_STATE: integer expression expected
Please correct me where I’m doing wrong.

I’m trying to check either New State is greater or Old state…. (0 Replies)

Discussion started by: kashif.live

2. Shell Programming and Scripting

expr: An integer value was expected

Hi,

I am trying to execute a simple script as below to compare a value from a file and copy that line based on a condition.

while read line
do
code_check = `expr substr «$line» 6 1`

if ; then
echo «${line}» >> /temp/bill/push_updated.dat
else
echo «line ignored»
fi
done <… (8 Replies)

Discussion started by: ramkiran77

3. UNIX for Dummies Questions & Answers

Integer expression expected error in script

When i run the following code i get an error that says Integer expression expected!
How do i fix this?

#!/bin/bash

if ;then
echo «wrong»
exit 1

fi

if ;then

for i in /dev;do

if ;then

echo $i
ls -l
fi (4 Replies)

Discussion started by: kotsos13

4. Shell Programming and Scripting

Error: integer expression expected

root@server01 # df -h | grep /tmp | awk {‘print $3}’
252M
root@server01 #

root@server01 # cat /usr/local/tmpchk.sh
#!/bin/sh

x=`df -h | grep /tmp | awk {‘print $3}’`

if ;

then

rm -fr /tmp/somefolder/

else

echo «its small» (2 Replies)

Discussion started by: fed.linuxgossip

5. Shell Programming and Scripting

if script error: integer expression expected

Hi, i am making a simple program with a optional -t as the 3rd parameter.
Submit course assignment -t dir

In the script, i wrote:
#!/bin/bash
echo «this is course: ${1}»
echo «this is assignment #: ${2}»
echo «late? : ${3}»
if then
echo «this is late»
fi

but this gives me a
:… (3 Replies)

Discussion started by: leonmerc

7. Shell Programming and Scripting

Display Error [: : integer expression expected

i have lunix 5.4
i make script to tack the export from database 11g by oracle user
the oracle sheel is /bin/bash
when run this script display this error
./daily_xport_prod: line 36:

the daily_xport_prod script

#! /bin/sh
#
ORACLE_HOME=/u01/appl/oracle/product/11.2.0/db_1
export… (8 Replies)

Discussion started by: m_salah

8. Fedora

«integer expression expected» error with drive space monitoring script

Hi guys,

I am still kinda new to Linux.

Script template I found on the net and adapted for our environment:

#!/bin/sh
#set -x
ADMIN=»admin@mydomain.com»
ALERT=10
df -H | grep -vE ‘^Filesystem|tmpfs|cdrom’ | awk ‘{ print $5 » » $1 }’ | while read output;
do
#echo $output
(2 Replies)

Discussion started by: wbdevilliers

9. Shell Programming and Scripting

integer expression expected error crontab only

I created a bash script that ran fine for awhile on a nightly crontab but then started crashing with commands not found, so I added

PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/bin/X11:/home/homedir/scripts/myscriptdir
export PATH
and now I don’t get those errors, but… (2 Replies)

Discussion started by: unclecameron

10. Shell Programming and Scripting

integer expression expected error

I’m a beginner so I might make beginner mistakes.
I want to count the «#define» directives in every .C file
I get the following errors:

./lab1.sh: line 5: ndef: command not found
./lab1.sh: line 6:
#!/bin/sh

for x in *.
do
ndef = ‘grep -c #define $x’
if ; then
(2 Replies)

Discussion started by: dark_knight

Comments

@gerroon

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

…ndroid

Now that Lil' Debi defaults to using /etc/init.d/rc 0 to shutdown, these
rc.d scripts need to be removed from any existing Debian chroot as well.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

Some standard enviroment variables are set by Android, then passed through to
the Debian environment unchanged.  That then causes a broken Debian
environment.  So these need to be set before starting the login shell.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

…ndroid

Now that Lil' Debi defaults to using /etc/init.d/rc 0 to shutdown, these
rc.d scripts need to be removed from any existing Debian chroot as well.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

Some standard enviroment variables are set by Android, then passed through to
the Debian environment unchanged.  That then causes a broken Debian
environment.  So these need to be set before starting the login shell.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

The existing kill logic looks for all processed that have a root of
/data/debian (aka $mnt).  /debian/shell is started outside of the chroot so
it have a root of /, and it wasn't getting killed.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

Some standard enviroment variables are set by Android, then passed through to
the Debian environment unchanged.  That then causes a broken Debian
environment.  So these need to be set before starting the login shell.

refs guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Oct 18, 2014

@eighthave

The existing kill logic looks for all processed that have a root of
/data/debian (aka $mnt).  /debian/shell is started outside of the chroot so
it have a root of /, and it wasn't getting killed.

refs guardianproject#131 guardianproject#131

@eighthave
eighthave

changed the title
Missing paths

«bash: [: : integer expression expected» when launching debian shell

Oct 24, 2014

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Jan 24, 2015

@eighthave

On some devices that I do not have, the embedded busybox `id -u` command is
failing to run, breaking this script's syntax.  This validates that $id
contains a number before testing whether it is equal to 0.

closes guardianproject#131 guardianproject#131

eighthave

added a commit
to eighthave/lildebi
that referenced
this issue

Feb 10, 2015

@eighthave

Понравилась статья? Поделить с друзьями:
  • Intel wifi 6 ax201 код ошибки 10
  • Integer division result too large for a float как исправить
  • Intel server error перевод
  • Intel server error майнкрафт
  • Intcazaudaddservice ошибка 258