Unix Cheatsheet 2

Here is a list of useful commands that I find myself having to look up fairly often. For more basic commands see Unix Command Cheatsheet

Move the contents of a folder one folder up and remove said folder

From the subfolder that you no longer need: mv * .[^.]* ..

Modifying hosts file (Mac/ Linux)

sudo vi /etc/hosts

Lists contents with permissions in octal format

  • stat -c "%a %n" * all files in a folder
  • stat -f '%a %n' <file> a specific file

MacOs

  • stat -f '%A %N' * all files in a folder
  • stat -f '%A %N' <file> a specific file

Prepend text to the beginning of a file

(echo I am first; cat foo.txt) > _foo.txt && mv {_,}foo.txt

Count the number of times a word appears on page

curl -s https://www.gutenberg.org/cache/epub/67098/pg67098 | sed -r 's/ /\n/g' | grep -i heffalump | wc -l

Create a file containing today’s date in a folder with the current year

cd src/content/"$(date +"%Y")" && printf "---\ndate: $(date +"%Y-%m-%d")\n---" >> $(date +"%F").md

Discard Standard Output

echo "don't print me" > /dev/null 2>&1

Native Environment variables and Global scripts

Unix also has global environment variables that can be accessed globally. Global scripts can be kept in /usr/local/bin and be accessed system wide.

these include:

  • $PATH system file paths (colon separtated)
  • $? exit code of previous command

Commands put at the end of a .bashrc file will be run every time a new terminal is opened.

Stopping Processes

  • lsof -i tcp:3000 gets all processes running on port 3000
  • kill <pid> ends the process <pid> (allows for clean up)
  • kill -3 <pid> quits the process <pid> (allows for clean up)
  • kill -9 <pid> force stops the process <pid>
  • pgrep <command> find command that is running by its command name
  • pkill <pid> kill process by <pid> returned from previous command