0

My script has a line that measures the number of instances of a process being run

procs=$(pgrep -f luminati | wc -l);

However, even though the content of $procs is a numeral, the shell script is not storing $procs as an integer. It is being stored as a string.

Therefore I cannot run conditionals like

if $procs > 3

Is there any way to convert this variable to integer type?

2
  • 1
    PS: shellcheck automatically detects this and other common problems. Commented Apr 2, 2018 at 16:34
  • Everything in shell is a string. You need to use the correct commands and operators that can treat strings as numbers. Commented Apr 2, 2018 at 17:27

2 Answers 2

2

In bash > is truncate which writes to a file. You probably have a file called 3 now. You should use the comparitor -gt:

if [[ "$procs" -gt 3 ]]; then
    ...
fi

Also, you don't have separate types for integers and strings.

Edit: As @chepner explained, for POSIX compatibility you should use single brackets:

if [ "$procs" -gt 3 ];
Sign up to request clarification or add additional context in comments.

4 Comments

LOL, indeed I had a file called 3 by using the > sign which I knew about but did not think in this context. But your solution is bang on. Thanks.
'>' is not truncate inside [[ ]], it's ascii comparison
@DiegoTorresMilano is right, > doesn't truncate inside [[ ]], however it does inside [ ]! It's always safer to use -gt in my opinion.
The existence of [[ strongly implies your shell also has ((...)). Use if [ "$procs" -gt 3 ]; for POSIX compatibility or if (( procs > 3 )); for readability.
2

Should be

if [[ "$procs" -gt 3 ]]
then
 ...
fi

1 Comment

You mean to use -gt rather than >?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.