Skip to content

Instantly share code, notes, and snippets.

@somahargitai
Last active May 26, 2023 11:22
Show Gist options
  • Save somahargitai/079bd88a34c4c077c28558dedc983cc7 to your computer and use it in GitHub Desktop.
Save somahargitai/079bd88a34c4c077c28558dedc983cc7 to your computer and use it in GitHub Desktop.
Terminal Cheatsheet

Terminal tips and tricks

↩cheatsheet list

For Windows commands check my other Gist

For a more detailed command list, check Freecodecamp's huge article

contents:

  1. My favourites
  2. Basics
  3. Advanced
  4. Editors
  5. Environment
  6. Win / Mac / GNU workarounds
  7. Shortcuts

1) My favourites

  • List the lines from a text (here: history) which contains a keyword (here: git):
history | grep git
history | awk '/git/ {print}'

Last 15 only:

history | grep git | head -n 15
  • get the folders updated since a given date:
find . -maxdepth 1 -type d -newermt "2023-05-24 00:00:00" |
awk -F/ '{print $NF}'
  • Show hidden files in Mac's file manager (Finder): Open Terminal and run the following script:
    defaults write com.apple.Finder AppleShowAllFiles true
    killall Finder

  • Count how many times a word appears in a file:

  cat PATH/TO/FILE/index.js | grep somefunkyword | wc -l

2) Basics

  • go to a folder cd folderName
  • leave the folder, go to its parent folder cd ..
  • go to the root folder cd ~
  • go to the home folder cd $HOME
  • create a new folder mkdir folderName
  • if you have an opened file or process in terminal and would like t o exit, you should try Control C or q

Main commands and operators

command            description
pwd see in terminal the current your current path (which folder you are in)
man pwd documentation of the command
cd, ls, ls -l, ls -a moving in folder structure (c hange d irectory), list folder content
mkdir, touch create folders and files
cat a.txt, less b.txt, more c.txt, awk '{print}' d.txt read file to standard output (practically: print to console). less and more create a scrollable print
env, printenv list environmental variables
date print date
history terminal command history (terminal-window related so don't trust it too much)
ifconfig list computer ip, environmental variables
grep search text. It can be used in terminal like grep text in filename see examples here but it is also very common to pipe an output to it. For example: history | grep code extracts all the commands from terminal history where we opened a file with VS Code
pipe | read the output of a function and pass it to another function see example here
tail -99 c.txt read last 99 lines of a file to standard output
wc index.html count characters, words and lines in a specific file
ls | wc -w count files/folders in a folder

More complicated commands with a typical example

command example description
sed sed -i 's/80/5000/g' target/tobeedited.txt find and replace text 80 to 5000 in a file
awk ls -la | awk '{print $3, $9}' show words from lines by their word count index
more about awk
  • folder name and date in this format: 536daysoftype - May 7
  ls -la | awk '{print NR $9 " - " $6 " "  $7 }'
  • longest line and its length
  ls -la | awk '{ if (length($0) > max) max = length($0) } END {print "length: " max "         - " $0}'
NR: Represents the current record number (line number) being processed.
NF: Represents the number of fields (columns) in the current record.
$0: Refers to the entire input record (the full line).
$1, $2, $3, etc.: Represent the individual fields (columns) of the input record. $1 refers to the first field, $2 to the second field, and so on.
FS: Specifies the input field separator (default is whitespace).
RS: Specifies the input record separator (default is newline).
OFS: Specifies the output field separator (used when printing fields).
ORS: Specifies the output record separator (used when printing records).
FILENAME: Contains the name of the current input file being processed.
FNR: Represents the record number (line number) within the current input file.
ARGC: Contains the total number of command-line arguments.
ARGV: An array that stores the command-line arguments passed to awk.

3) Advanced

  • find your running server and stop it You can do it by listing the running processes on your computer. If you have a running server (like Node.js or Tomcat) on a port (like 8080, 3000 etc.), you will see in the list that your server is there, like 0.0.0.0:8080. Copy the identifier of that process and stop it like below!

    GNU/Linux and Mac
    sudo lsof -i -P -n | grep LISTEN
    kill 27746

  • ping an API with curl : instead of opening a URL in the browser, or using Postman, you can do this in the terminal.
    curl https://github.com
    curl -i -X POST -H "Content-Type: multipart/mixed" -F "uploadParams={\"one_parameter\":\"one_value\"};type=application/json" -F "file=@/Users/user/Downloads/gangstercar.jpg" http://localhost:7000/myapplication/services/myendpoint

4) Editors

You may use VS Code or Jetbrains for your code, but there are also command line editors. Vim and Emacs are old, powerful ones but it is not so easy to work with them. nano is more handy. Of course you can also avoid the usage of command line editors.

important: Git may open the editor in some situations. The default file editor of Git is Vim. If you are not comfortable with Vim, change your default code editor in Git settings to nano or VS code:
git config --global core.editor "nano"
git config --global core.editor "code"

5) Bash shell scripts

Shell scripts, like bash are (usually) simple scripts, which you can run in your terminal. It is the "language of the terminal", so you don't have to install anything. Here is an example you can save as fruits.sh and try:

#! /bin/bash

WELCOME="Welcome to bash!"
echo $WELCOME

for x in $@
  do
    echo "I got a parameter: $x"
    if [[ $x == "strawberry" ]]
    then
      echo "it is a fruit"
    else
      echo "need some cream on the top?"
    fi
  done

Run bash script:

  bash ./fruits.sh strawberry chocolate

Most common shells on Linux / Mac

  • sh or Bourne shell
  • bash or Bourne Again Shell
  • zsh or z-shell (originates from the name of professor Zhong Shao)

note: for shell script files you can use always .sh extension (it is not required, just convention)

6) Environment

For handling environmental variables in Windows command line (CMD), check out this StackOverflow article.

Create environmental variables

You can create an environmental variable on Linux / Mac with
export PORT=8080
If you don't need it any more, remove it with
unset PORT.

You can use bash to define environmental variables and script you use often in an envsetter.sh

#!/bin/sh

#Remote
#echo - Setting variables  

export HOPHOPHOP_DB_PW="gangnam-style"
export HOPHOPHOP_DB_HOST="jdbc:postgresql://localhost:2345/postgres?"

alias runjacoco='mvn clean org.jacoco:jacoco-maven-plugin:prepare-agent install'
alias runsonar='mvn sonar:sonar'

unset HOPHOPHOP_DB_HOST

The main place to set environmental variables and Path is the .bash_profile in the root folder: ~/.bash_profile

PATH=${PATH}:~/bin
PATH=${PATH}:/usr/local/bin

export MYVARIABLE=soma/text/for/you

Starting your Mac will run .bash_profile. If you would like to run it without restart, you should run it:

source ~/.bash_profile

Certificates

install certificate files
sudo keytool -import -alias CERTIFICATE_NAME -file "CERTIFICATE_FILENAME.cer" -keystore cacerts -storepass changeit

7) Tools to be installed

  • Homebrew and wget

    It is a just a must to have the number one package manager and wget for recursive resource downloads. Follow Homebew website to install brew and wget:

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install wget

Homebrew services is also essential to maintain services on you Mac. You can install, start, stop, view background services like redis or mysql:

brew services start redis
brew services restart redis
brew services stop redis
brew services list
  • Tree View folder structure in terminal is just a must: brew install tree

7) Shortcuts

  • terminal clear: Command + K
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment