Skip to content

alexiscrack3/bash-cheat-sheet

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 

Repository files navigation

Bash Cheat Sheet

A collection of some of the most useful bash commands

Table of Contents

  1. File System
  2. Systen Info
  3. Process Management
  4. Permissions
  5. Networking
  6. Text Processing
  7. Searching
  8. Compression
  9. Shortcuts
  10. Redirections
  11. Others

File System

Listing Directories and Files

List items in current directory.

ls

List items with pattern in current directory.

ls <pattern>

List items in current directory in a single column.

ls -1

List items in current directory and show in long format to see perimissions, size, and modification date.

ls -l

List items in human readable size.

ls -h

List all items in current directory, including hidden files.

ls -a

List directory entries instead of contents.

ls -d <directory>

List only hidden files.

ls -ld .??*

-rw-r--r--@ the at symbol signifies that the file was downloaded from the internet, etc.

Changing Working Directory

Change current directory to directory.

cd <directory>

Change directory to home.

cd

Go up one directory.

cd ..

Go to the root directory.

cd /

Go to to your home directory.

cd ~

Go to the last directory you were just in.

cd -

Add path to directory stack.

pushd <directory>

Go back to the directory most recently stored by the pusdh command.

popd

View directory stack.

dirs

Making Directories

Make directory.

mkdir <directory>

Create or update file.

touch <file>

Removing Directories and Files

Remove empty directory.

rmdir <directory>

Remove directory recursively.

rm -r <directory>

Ignore nonexistent files, never prompt.

rm -f <directory>

Remove file.

rm <file>

Prompt before every removal.

rm -i <file>

Remove files that match a pattern.

rm <pattern>

Opening Directories and Files

Open current directory.

open .

Open files and directories.

open <path>

Specifies the application to use for opening the file.

open <file> -a <bin>

Causes the file to be opened with the default text editor, as determined via LaunchServices.

open -t <file>

Copying Files

Copy file1 to file2.

cp <file1> <file2>

Copy directory dir1 to dir2 recursively.

cp -r <dir1> <dir2>

Moving Directories and Files

Move (rename) path1 to path2.

mv <path1> <path2>

Move files form path to a different path.

mv <path>* <path>

Move hidden files from path to different path.

mv <path>.* <path>

Linking Files

Create hard link

ln <file> <link>

Create symbolic link.

ln -s <file> <link>

Displaying the Contents of a File

Output the contents of file.

cat <file>

View file with page navigation.

less <file>

Output the first 10 lines of file.

head <file>

Output the first 3 lines of file.

head -3 <file>

Output the last 10 lines of file.

tail <file>

Output the last 3 lines of file.

tail -3 <file>

Output the contents of file as it grows, starting with the last 10 lines.

tail -f <file>

Commands

Execute command for all directories or files in a given path.

find <path> -type <type> -exec chmod 644 {} \;

Execute command for all directories or files in a given path.

find <path> -type <type> -iname "*.csv" -exec cp {} ~/csv_files/ \;

Execute command for all directories or files in a given path.

find <path> -type <type> | xargs <bin>

Execute command for all directories or files in a given path and prints each command that will be executed.

find <path> -type <type> | xargs -t <bin>

Execute command for all directories or files in a given path and prints the command to be executed and prompts the user to run it.

find <path> -type <type> | xargs -p <bin>

Change permissions for all files, skipping dirs.

find . -type f | xargs chmod 664

Change permissions for all dirs, skipping files.

find . -type d | xargs chmod 755

Change permissions for all dirs with whitespaces, skipping files.

find . -type d -print0 | xargs -0 chmod 755

Find directories with permissions other than 664.

find -type f -not -perm 664

Find directories with permissions other than 755.

find -type d -not -perm 755

Count number of directories in a specific directory. Descend at most n directory levels below the command line arguments.

find -type d -maxdepth n | wc -l

Aliases

Create an alias for a command.

alias <name>="<command>"

Print alias.

alias <name>

System Info

Show system’s host name.

hostname

Shut down machine.

shutdown

Restart machine.

reboot

Show the current date and time.

date

Display how long the system has been running.

uptime

Display how long the system has been running.

w

Who you are logged in as.

whoami

Show the manual for bin.

man <bin>

Show free disk space.

df

Show free disk space with human readable size.

df -h

Show directory space usage.

du <file>

Show directory space usage with human readable size.

du -h <file>

Count number of lines/words/characters in file.

wc <file>

Count number of bytes in file.

wc -c <file>

Count number of lines in file.

wc -l <file>

Count number of characters in file.

wc -m <file>

Count number of words in file.

wc -w <file>

Show possible locations of bin.

whereis <bin>

Where the bin is located.

which <bin>

Print symlink free path as well.

which -s <bin>

Show this month's calendar.

cal

Show this years's calendar.

cal <year>

Process Management

Display all currently active processes.

ps

Display all running processes.

top

Sort processes by primary sort key in descending order.

top -o <key>

Sort processes by cpu in descending order.

top -u

Kill process id pid.

kill <pid>

Force kill process id pid.

kill -9 <pid>

kill all processes by name.

killall <name>

Kills process by port number.

lsof -P | grep ':<port>' | awk '{print $2}' | xargs kill -9

Permissions

Changing Permissions

Change permissions of file to ugo - u is the user's permissions, g is the group's permissions, and o is everyone else's permissions. The values of u, g, and o can be any number between 0 and 7.

  • 7 — full permissions
  • 6 — read and write only
  • 5 — read and execute only
  • 4 — read only
  • 3 — write and execute only
  • 2 — write only
  • 1 — execute only
  • 0 — no permissions
chmod <ugo> <path>

User can read and write - good for files.

chmod 600 <path>

User can read, write, and execute - good for scripts.

chmod 700 <path>

User can read and write, and everyone else can only read - good for web pages.

chmod 644 <path>

User can read, write, and execute, and everyone else can read and execute - good for programs that you want to share.

chmod 755 <path>

Change owner and group-related information for a file or directory.

chown <user> <path>

Making Executables

Add the executable bit (x) to the user, group and others.

chmod +x <file>

RemoveAdd the executable bit (x) to the user, group and others.

chmod -x <file>

Networking

Ping host and output results.

ping <host>

Get information for domain.

whois <host>

Get DNS information for domain

dig <domain>

Reverse lookup host

dig -x host

Sending Requests

Make a basic GET request to the specifed URI.

curl <uri>

Include HTTP-Header information in the output.

curl --include <uri>

Pass user credential to basic auth.

curl --user "username:password" <uri>

Send a header.

curl --header "Authorization: 12345" <uri>

Show more output.

curl -v <uri>
     --verbose

Copying Remote Files

Secure copy a file from remote server to the directory on your machine.

scp user@host:file <directory>

Secure copy a file from your machine to the directory on a remote server.

scp file user@host:<directory>

SSH

Connect to host as user.

ssh user@host

Connect to host on port as user.

ssh -p port user@host

Processes

List all processes running on port.

lsof -i :<port>

List all processes running on tcp port.

lsof -i tcp:<port>

List process using a file.

lsof <file>

Text Processing

Process text files. Awk assigns some variables for each data field found:

  • $0 for the whole line.
  • $1 for the first field.
  • $2 for the second field.
  • $n for the nth field.
awk '{print $n}' <file>

Searching

Search for pattern in directory.

grep <pattern> <directory>

Search recursively for pattern in directory.

grep -r <pattern> <directory>

Case-insensitive search for pattern in directory.

grep -i <pattern> <directory>

Prefix output with line numbers.

grep -n <pattern> <directory>

Select non-matching lines.

grep -v <pattern> <directory>

Only print a count of matching lines.

grep -c <pattern> <directory>

Find directories or files in system.

find <path>

Find a file that is a certain type. Possible types: d, t, l.

find <path> -type <type>

Find a file by name but the match is case sensitive.

find <path> -type <type> -name "<pattern>"

Find a file by name but the match is case insensitive.

find <path> -type <type> -iname "<pattern>"

True if the current file or directory is empty.

find <path> -type <type> -empty

Find all occurrences of PATTERN and replace them with REPLACEMENTE in a file. 's' means substitude.

There are four types of substitutions:

  • g, replace all occurrences.
  • A number, the occurrence number for the new text that you want to substitute.
  • p, print the original content.
  • w, write the results to a file.
sed 's/<pattern>/<replacement>/[<flags>]'

Redirect output to new file

sed 's/<pattern>/<replacement>/[<flags>]' <file>

Find and replace all ocurrences in the same file

sed -i.bak 's/<pattern>/<replacement>/[<flags>]' <file>

Print each line that contains a pattern match, use -n option to print the modified lines only.

sed -n 's/<pattern>/<replacement>/p' <file>

Limit the sed command to process specific lines.

sed '1s/<pattern>/<replacement>/[<flags>]' <file>

Search backward in history (reverse-i-search).

ctrl + r

Search forward in history (reverse-i-search).

ctrl + s

Cancel current search (reverse-i-search).

ctrl + g

Compression

Create a tar containing files.

tar cf <file>.tar <files>

Extract the files from tar.

tar xf <file>.tar

Create a tar with Gzip compression.

tar czf <file>.tar.gz <files>

Extract a tar using Gzip.

tar xzf <file>.tar.gz

Compresses file and renames it to file.gz.

gzip <file>

Decompresses Gzip back to file.

gzip -d <file>.gz

List archive files (verbose format).

unzip -v <file>.zip

List archive files (short format).

unzip -l <file>.zip

Shortcuts

Move cursor to beginning of line.

ctrl + a

Move cursor to end of line.

ctrl + e

Cut everything from line start to cursor.

ctrl + u

Cut everything from the cursor to end of the line.

ctrl + k

Cut one word backwards using white space as delimiter.

ctrl + w

Paste whatever was cut by the last cut command.

ctrl + y

Kill whatever you are running.

ctrl + c

Clears the screen.

ctrl + l

Clears the screen.

cmd + k

Redirections

Redirect the standard output (stdout) of command to a file.

<command> > file

Same as <command> > file. 1 is the default file descriptor for stdout.

<command> 1> file

Redirect the standard error (stderr) of command to a file. 2 is the default file descriptor for stderr.

<command> 2> file

Append stdout of command to a file.

<command> >> file

Append stderr of command to a file.

<command> 2>> file

Redirect stdout and stderr to a file.

<command> &> file

Redirect stdout and stderr to a file.

<command> > file 2>&1

Another way to redirect both stdout and stderr of command to a file. This is not same as <command> 2>&1 > file. Redirection order matters!

<command> > file 2>&1

Discard stdout of command.

<command> > /dev/null

Discard stderr of command.

<command> 2> /dev/null

Discard stdout and stderr.

<command> &> /dev/null

Redirect the contents of the file to the stdin of command.

<command> < file

Others

Print a string.

echo "<string>"

Prints exit code of previous command.

echo $?

Append stdout of command to a file.

<command> >> <file>

Show present working directory.

pwd

Print out a list of all environment variables.

env

Clear the terminal screen.

clear

Run the specified command with the given arguments. When command finishes, time writes timing statistics about this command run.

time <command>

Add directory to the beginning of the $PATH environment variable.

PATH=$PATH:<dir>

Add directory to the ending of the $PATH environment variable.

PATH=<dir>:$PATH

Provide copying to the pasteboard.

pbcopy < <file>

Provide copying to the pasteboard.

cat <file> | pbcopy

Provide pasting to the pasteboard.

pbpaste

Split a file into pieces. The default size for each split file is 1000 lines.

split

Evaluate a file or resource as a script.

source <file>

An arbitrary precision calculator language.

bc

Do not print the normal GNU bc welcome.

bc -q

Run left-hand command and then right-hand command, regardless of success of left-hand command.

<command>; <command>

Run right-command if left-hand command succeeded.

<command> && <command>

Run right-hand command if left-hand command failed.

<command> || <command>

Run command in background.

<command> &

List recent commands.

history

Get the weather forecast in your current location based on your ip address.

curl wttr.in

Get the weather in a different city. Replace any spaces in the name with a + or underscode.

curl wttr.in/<city>

Print a sequence of numbers.

seq 1 10

Execute long running script and refocus window when it's done.

<command>; open -a iTerm

Print last executed command.

!!

About

A collection of some of the most useful bash commands

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published