Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

I want to execute this condition

while [ $(cat /path_of a file/) -eq 1 ]

The condition is only correct if

$(cat /path_of a file/) 

is an integer and not a string !

How can I overcome this problem ?

share|improve this question

2 Answers 2

You can do this with = operator, like [ $(cat /path_of a file/) = 1 ]. It compares string representations of both arguments so it will work in all cases.

Using -eq instead of string comparison may be preferable in some cases ([ 01 -eq 1 ] is true while [ "01" = 1 ] is not) but in most cases it's just more dangerous. If, on the other hand, you really need integer comparison, you should use @Gnouc suggestion.

share|improve this answer
    
better use quotes: [ "$(cat file)" = 1 ] -- if the file is empty, you'll get a syntax error otherwise – glenn jackman Apr 6 '14 at 23:27

Variable in bash is untyped. If you want the condition to always get evaluated with integers, you can use delcare -i to make variable always an integer. From bash manpage:

declare [-aAfFgilrtux] [-p] [name[=value] ...]
.....
-i     The variable is treated as an integer; arithmetic evaluation
       (see ARITHMETIC EVALUATION above) is performed  when the variable
       is assigned a value.

So your example becomes:

declare -i number
number="$(cat /path_of a file/)"

while [ "$number" -eq 1 ]

A note that if you have bash version 4.x, you should use new test [[...]] instead of [...].

share|improve this answer
    
[[ is available in older versions of bash as well. – chepner Apr 6 '14 at 14:35

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.