Unix Shell

Created:

Updated: 29 September 2023

Searching

You can use grep to search in a file

grep "hello" ./hello.txt

Or recursively through a directory:

grep -R "hello" ./hello

And using a RegEx

grep -R ^hello

Or case inensitive with -i or for full words with -w

You can even search for something in the output of a command using a pipe (|)

echo "hello world" | grep "world"

Processes

List Processes

To kill a process you can first list running processes

lsof

To get the PID of a process you can use lsof along with grep, e.g. find a node process:

lsof | grep node

Find A Process on a Current Port

E.g for a processs running on port 4001

lsof -i:4001

You can also just get the port by adding -t:

lsof -t -t:4001

Kill a Process by PID

You can kill a process using it’s PID using:

kill 1234

Or with -9 to force

kill -9 1234

Kill a Process by Port

You can kill a process that’s listening on a port by first getting the PID of the process with lsof -t -i:<PORT NUMBER> and pass it into the kill command, e.g. for port 4000

kill $(lsof -t -i:4000)

Jobs/Background Processes

Start a process, e.g. ping

ping google.com

The use ctrl+z to suspend the task into the background

You can now use the terminal and start other jobs

Once jobs are running you can use jobs to view runnning jobs:

jobs

# which outputs
[1]    suspended  ping google.com
[2]  - suspended  ping other.com
[3]  + suspended  ping hello.com

Jobs can be resumed using fg for the most recent job, or fg %<JOB NUMBER> to resume a specific job

For example, resuming the ping hello.com can be done with:

fg %3

You can use cd to move to specific folders relatively

cd ../other-folder/my-folder

Or even from the user home directory by prefixing with ~

cd ~/my-stuff

And you can use - to just swap back to the last directory

# before, in apps/stuff, now in apps/something-else
cd -
# after, now in apps/something-else