I'm running two minecraft servers on my machine. I want to know what the pid is of a single mc server that is running and put it to file so that I can kill it later. So for this example I only want to know what the PID is of World2 nothing else and save it to file.
When I perform a command
ps h -o pid,cmd -u minecraft
I get the following results
31416 /usr/lib/jvm/java-8-oracle/jre/bin/java -Xmx2G -Xms1G -jar /data/mc-server/World1/minecraft_server.jar nogui
31706 /usr/lib/jvm/java-8-oracle/jre/bin/java -Xmx6G -Xms4G -jar /data/mc-server/World2/craftbukkit.jar nogui
I then pipe to grep using this command
grep World2
This is where I get into difficulties, I then pipe to to get a single result back. I tried the following but just can't get it.
awk '{print $1 > world2.pid}'
So my full command is:
ps h -o pid,cmd -u minecraft | grep World2 | awk '{print $1 > world2.pid}'
I get the following error:
awk: cmd. line:1: {print $1 > world2.pid}
awk: cmd. line:1: ^ syntax error
Best Answer
If you want to put the redirection inside awk, you need to put the filename in quotes - otherwise, awk treats it as a variable rather than a literal string:
However it would be more conventional to let awk write to standard output, and redirect that i.e.
Alternatively, you may want to look at using
pgrep
for the whole task e.g. something like