Cheatsheet - Shell Processes
ps
ps accepts different types of options:
- UNIX options: with a preceding dash. (e.g.
ps -e) - BSD options: without a preceding dash. (e.g.
ps aux) - GNU long options: with two preceding dashes.
Note that ps -aux is distinct from ps aux.
Start Daemon
if kill -0 $pid > /dev/null 2>&1; then
echo Database is already running ...
else
echo Starting Database ...
bin/mongod &
fi
Step by Step:
kill -0 $pid:-0for testing if the pid is available to kill. It will return0if you can kill<pid>,1if<pid>is invalid or you do not have access.... > /dev/null 2>&1: redirect the output to/dev/null, a blackhole.2stands forSTDERR,1forSTDOUT. This command means redirectSTDOUTto/dev/null, and redirectSTDERRtoSTDOUT(which is/dev/null), so bothSTDOUTandSTDERRwill be quiet. Remember the&before destination.bin/mongod &: if it is not running, start the daemon. Remember the&for running in the background.
Wait before it is up:
while true; do
sleep 1
if pgrep mongod; then
break
fi
done
Stop Daemon
Similar to the previous section.
if kill -0 $pid_mongod > /dev/null 2>&1; then
echo Stopping mongod Server ...
kill -9 $pid_mongod
else
echo No mongod Server to stop ...
fi
Jobs / Foreground / Background
List all jobs:
$ jobs
Run something in background
$ <command> &
Foreground to Background:
[Ctrl + z]
$ bg
Background to Foreground:
# something is running in background
$ fg
Ctrl-C vs Ctrl-V
Ctrl-C: to (politely) kill a process with signalSIGINT; cannot be resumed.Ctrl-Z: to suspend a process with the signalSIGTSTP, like a sleep signal, can be undone and the process can be resumed:fg: resume in foregroundbg: resume in background
Run at a specific time
$ at 2:00 PM
cowsay 'hello'
(CTRL + D)
the command will run at 2 PM
List all jobs
$ at -l
1 Tue Apr 12 14:00:00 2016
Remove a job
$ at -r 1
Nohup
Run command in background and redirect output to file.
$ nohup command > output &
nohup is a POSIX command to ignore the HUP (hangup) signal, enabling the command to keep running after the user who issues the command has logged out. The HUP (hangup) signal is by convention the way a terminal warns depending processes of logout. Then use
$ tail -f output
to print the last few lines of the output.
How to put an already-running process under nohup?
Ctrl-zto pause the program and get back to the shellbgto run it in the backgrounddisown -h JOB_NUMBER; whereJOB_NUMBERand be found withjobscommand.
Rename extensions of multiple files
for file in *.mdx; do mv -- "$file" "${file%.mdx}.md"; done