简体   繁体   English

Bash单行嵌套for循环将比较变量作为命令

[英]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. 我相信我的错误是在do if ($i -gt 100)区域,但我还没能弄清楚。

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. 我的输出就是将进程ID作为命令。

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. 谢谢。

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 ). 请注意,在[]之前和之后有一个空格,这是必要的,否则您将收到语法错误(因为[是在/usr/bin test的链接)。

The relevant manapge would be man test , as [ is test . 相关的manapge将是man test ,因为[test

Also, but this has nothing to do with the question, I recommend switchting from 此外,但这与问题无关,我建议切换

`command`

to

$(command)

in bash. 在bash中。

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: 目前还不清楚你的脚本试图做什么(发布的答案在我的系统上没有产生输出)但是如果你想打印大于100的所有PID,你可以这样做:

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

只需在括号和表达式之前和之后添加空格

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM