シェルスクリプトの単体試験でたまに使用するのでメモしておきます。
実施環境:
Linux
[testuser@testhost ~]$ uname -a
Linux testhost 4.18.0-147.8.1.el8_1.x86_64 #1 SMP Thu Apr 9 13:49:54 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
[testuser@testhost ~]$ echo $SHELL
/bin/bash
シェルスクリプトの単体試験等で、たまに特定の文字列を含むダミープロセスを作成したいときがあります。
そのような場合、yesコマンドを使用すると簡単に実現できます。
Linux
[testuser@testhost ~]$ ps aux | grep -v grep | grep "test proc"
[testuser@testhost ~]$
[testuser@testhost ~]$ yes test proc >/dev/null 2>&1 &
[1] 2770
[testuser@testhost ~]$ i=$!
[testuser@testhost ~]$ echo $i
2770
[testuser@testhost ~]$ ps aux | grep -v grep | grep "test proc"
testuser 2770 99.7 0.0 217040 828 pts/0 R 21:10 4:42 yes test proc
[testuser@testhost ~]$ kill -9 $i
[testuser@testhost ~]$
[1]+ Killed yes test proc > /dev/null 2>&1
[testuser@testhost ~]$ ps aux | grep -v grep | grep "test proc"
[testuser@testhost ~]$
yesコマンドは指定した文字列を標準出力に出力し続けるコマンドです。
含みたい文字列を引数に指定し、出力は全て"/dev/null"に捨て、"&"でバックグラウンドで実行しています。
"$!"は実行したコマンドのプロセスIDが格納される変数です。
なお、別窓で実行できるなら、フォアグラウンドで実行し、不要になったらCtrl+Cで停止するでもよいです。