Sean Mackert
Sean Mackert

Reputation: 13

Bash single-line nested for-loop is taking comparison variable as a command

I believe my error is in do if ($i -gt 100) area but I havent been able to figure it out.

My input is:

for i in `ps | cut -d ' ' -f1`; do if ($i -gt 100); then echo $i; fi; done

My output is this where the process IDs have been taken as commands.

bash: 13968: command not found
bash: 21732: command not found
bash: 21733: command not found
bash: 21734: command not found

How can I fix this and what is the relevant man page that I should read up on? Thank you.

Upvotes: 1

Views: 252

Answers (3)

Ed Morton
Ed Morton

Reputation: 203985

It's not clear what your script is trying to do (the posted answers produce no output on my system) but if you want to print all PIDs that are greater than 100, here's how you'd do that:

$ ps | awk '$1 > 100{print $1}'
PID
314024
217880
230804
217084
263048
260788
218016
313464
201556
200732

Upvotes: 1

Yassin Kisrawi
Yassin Kisrawi

Reputation: 197

just add spaces after and before brackets and the expression

for i in `ps | cut -d ' ' -f1`; do if [ $i -gt 100 ]; then echo $i; fi; done

Upvotes: 0

Nidhoegger
Nidhoegger

Reputation: 5232

if ($i -gt 100)

should be changed to

if [ $i -gt 100 ]

Note that there is a space before and after [], this is neccessary, otherwise you will get a syntax error (its because [ is a link to test in /usr/bin).

The relevant manapge would be man test, as [ is test.

Also, but this has nothing to do with the question, I recommend switchting from

`command`

to

$(command)

in bash.

Upvotes: 2

Related Questions