logo

Shell Cheatsheet - 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: -0 for testing if the pid is available to kill. It will return 0 if you can kill <pid>, 1 if <pid> is invalid or you do not have access.
  • ... > /dev/null 2>&1: redirect the output to /dev/null, a blackhole. 2 stands for STDERR, 1 for STDOUT. This command means redirect STDOUT to /dev/null, and redirect STDERR to STDOUT(which is /dev/null), so both STDOUT and STDERR will 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 signal SIGINT; cannot be resumed.
  • Ctrl-Z: to suspend a process with the signal SIGTSTP, like a sleep signal, can be undone and the process can be resumed:
    • fg: resume in foreground
    • bg: 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-z to pause the program and get back to the shell
  • bg to run it in the background
  • disown -h JOB_NUMBER; where JOB_NUMBER and be found with jobs command.

Rename extensions of multiple files

for file in *.mdx; do mv -- "$file" "${file%.mdx}.md"; done