[英]iteration of for loop in shell script
I have a simple script that uses a for loop where I want to take the value of a variable and assign it to another command and kill the screen. 我有一个简单的脚本,该脚本使用for循环,在该循环中,我想获取变量的值并将其分配给另一个命令并杀死屏幕。 The script goes as
脚本如下
#!/usr/bin/sh/
echo 'I am going to kill the screens now';
for j in $(seq 1 1 10)
do
i=$(grep -oP '.*?(?=\.)');
echo $i
screen -S $i -p 0 -X quit
done <file1.txt
echo 'exiting...'
file1.txt file1.txt
There are screens on:
4974.eth2 (Detached)
5105.eth11 (Detached)
4990.eth3 (Detached)
5006.eth5 (Detached)
5054.eth8 (Detached)
5070.eth9 (Detached)
5038.eth7 (Detached)
5022.eth6 (Detached)
8 Sockets in /var/run/screen/S-root.
So here, I am iterating through 10 lines and assigning the value of i=whatever before a period(.). 所以在这里,我要遍历10行,并在period(。)之前分配i = what的值。 eg.
例如。
4974
. 4974
。 Then placing 4974
in screen command and killing it. 然后将
4974
放到屏幕命令中并杀死它。 The problem here is, it is reading and grepping all the lines at a time and in the value of i
it places as 4974 5105 4990 5006 5054 5070 5038 5022
in the screen command and it obviously it cannot find a screen id like that and doesn't kill any screen. 这里的问题是,它一次读取并抓取所有行,并将其
i
的值作为4974 5105 4990 5006 5054 5070 5038 5022
放置在screen命令中,显然它找不到这样的屏幕ID,并且没有不会杀死任何屏幕。 How do i iterate the loop such that at a time it takes one id ie.value of i=4974
and place only that in the screen command so that it will kill it.. Let me know if you understand my question correctly. 我如何迭代该循环,以便一次使用一个id(
i=4974
并将其仅放置在screen命令中,以便将其杀死。让我知道您是否正确理解了我的问题。
Try this: 尝试这个:
awk -F'[. ]+' '/Detached/ {print $2}' file.txt | while read i
do
echo "$i"
screen -S "$i" -p 0 -X quit
done
Instead of iterating over a counter, iterate over your results directly: 无需遍历计数器,而是直接遍历结果:
set -f # disable globbing, so globs in grep's output aren't expanded
echo 'I am going to kill the screens now' >&2
for i in $(grep -oP '.*?(?=\.)'); do
echo "$i"
screen -S "$i" -p 0 -X quit
done <file1.txt
echo 'exiting...' >&2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.