Cheat Sheet for BASH

  1#!/bin/bash
  2##############################################################################
  3# SHORTCUTS and HISTORY
  4##############################################################################
  5
  6CTRL+A  # move to beginning of line
  7CTRL+B  # moves backward one character
  8CTRL+C  # halts the current command
  9CTRL+D  # deletes one character backward or logs out of current session, similar to exit
 10CTRL+E  # moves to end of line
 11CTRL+F  # moves forward one character
 12CTRL+G  # aborts the current editing command and ring the terminal bell
 13CTRL+H  # deletes one character under cursor (same as DELETE)
 14CTRL+J  # same as RETURN
 15CTRL+K  # deletes (kill) forward to end of line
 16CTRL+L  # clears screen and redisplay the line
 17CTRL+M  # same as RETURN
 18CTRL+N  # next line in command history
 19CTRL+O  # same as RETURN, then displays next line in history file
 20CTRL+P  # previous line in command history
 21CTRL+Q  # resumes suspended shell output
 22CTRL+R  # searches backward
 23CTRL+S  # searches forward or suspends shell output
 24CTRL+T  # transposes two characters
 25CTRL+U  # kills backward from point to the beginning of line
 26CTRL+V  # makes the next character typed verbatim
 27CTRL+W  # kills the word behind the cursor
 28CTRL+X  # lists the possible filename completions of the current word
 29CTRL+Y  # retrieves (yank) last item killed
 30CTRL+Z  # stops the current command, resume with fg in the foreground or bg in the background
 31
 32ALT+B   # moves backward one word
 33ALT+D   # deletes next word
 34ALT+F   # moves forward one word
 35ALT+H   # deletes one character backward
 36ALT+T   # transposes two words
 37ALT+.   # pastes last word from the last command. Pressing it repeatedly traverses through command history.
 38ALT+U   # capitalizes every character from the current cursor position to the end of the word
 39ALT+L   # uncapitalizes every character from the current cursor position to the end of the word
 40ALT+C   # capitalizes the letter under the cursor. The cursor then moves to the end of the word.
 41ALT+R   # reverts any changes to a command you’ve pulled from your history if you’ve edited it.
 42ALT+?   # list possible completions to what is typed
 43ALT+^   # expand line to most recent match from history
 44
 45CTRL+X then (   # start recording a keyboard macro
 46CTRL+X then )   # finish recording keyboard macro
 47CTRL+X then E   # recall last recorded keyboard macro
 48CTRL+X then CTRL+E   # invoke text editor (specified by $EDITOR) on current command line then execute resultes as shell commands
 49
 50BACKSPACE  # deletes one character backward
 51DELETE     # deletes one character under cursor
 52
 53history   # shows command line history
 54!!        # repeats the last command
 55!<n>      # refers to command line 'n'
 56!<string> # refers to command starting with 'string'
 57
 58exit      # logs out of current session
 59
 60
 61##############################################################################
 62# BASH BASICS
 63##############################################################################
 64
 65env                 # displays all environment variables
 66
 67echo $SHELL         # displays the shell you're using
 68echo $BASH_VERSION  # displays bash version
 69
 70bash                # if you want to use bash (type exit to go back to your previously opened shell)
 71whereis bash        # locates the binary, source and manual-page for a command
 72which bash          # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)
 73
 74clear               # clears content on window (hide displayed lines)
 75
 76
 77##############################################################################
 78# FILE COMMANDS
 79##############################################################################
 80
 81
 82ls                            # lists your files in current directory, ls <dir> to print files in a specific directory
 83ls -l                         # lists your files in 'long format', which contains the exact size of the file, who owns the file and who has the right to look at it, and when it was last modified
 84ls -a                         # lists all files in 'long format', including hidden files (name beginning with '.')
 85ln -s <filename> <link>       # creates symbolic link to file
 86readlink <filename>           # shows where a symbolic links points to
 87tree                          # show directories and subdirectories in easilly readable file tree
 88mc                            # terminal file explorer (alternative to ncdu)
 89touch <filename>              # creates or updates (edit) your file
 90mktemp -t <filename>            # make a temp file in /tmp/ which is deleted at next boot (-d to make directory)
 91cat <filename>                # prints file raw content (will not be interpreted)
 92any_command > <filename>      # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)
 93more <filename>               # shows the first part of a file (move with space and type q to quit)
 94head <filename>               # outputs the first lines of file (default: 10 lines)
 95tail <filename>               # outputs the last lines of file (useful with -f option) (default: 10 lines)
 96vim <filename>                # opens a file in VIM (VI iMproved) text editor, will create it if it doesn't exist
 97mv <filename1> <dest>         # moves a file to destination, behavior will change based on 'dest' type (dir: file is placed into dir; file: file will replace dest (tip: useful for renaming))
 98cp <filename1> <dest>         # copies a file
 99rm <filename>                 # removes a file
100find . -name <name> <type>    # searches for a file or a directory in the current directory and all its sub-directories by its name
101diff <filename1> <filename2>  # compares files, and shows where they differ
102wc <filename>                 # tells you how many lines, words and characters there are in a file. Use -lwc (lines, word, character) to ouput only 1 of those informations
103sort <filename>               # sorts the contents of a text file line by line in alphabetical order, use -n for numeric sort and -r for reversing order.
104sort -t -k <filename>         # sorts the contents on specific sort key field starting from 1, using the field separator t.
105rev                           # reverse string characters (hello becomes olleh)
106chmod -options <filename>     # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID)
107gzip <filename>               # compresses files using gzip algorithm
108gunzip <filename>             # uncompresses files compressed by gzip
109gzcat <filename>              # lets you look at gzipped file without actually having to gunzip it
110lpr <filename>                # prints the file
111lpq                           # checks out the printer queue
112lprm <jobnumber>              # removes something from the printer queue
113genscript                     # converts plain text files into postscript for printing and gives you some options for formatting
114dvips <filename>              # prints .dvi files (i.e. files produced by LaTeX)
115grep <pattern> <filenames>    # looks for the string in the files
116grep -r <pattern> <dir>       # search recursively for pattern in directory
117head -n file_name | tail +n   # Print nth line from file.
118head -y lines.txt | tail +x   # want to display all the lines from x to y. This includes the xth and yth lines.
119
120
121##############################################################################
122# DIRECTORY COMMANDS
123##############################################################################
124
125
126mkdir <dirname>               # makes a new directory
127rmdir <dirname>               # remove an empty directory
128rmdir -rf <dirname>           # remove a non-empty directory
129mv <dir1> <dir2>              # rename a directory from <dir1> to <dir2>
130cd                            # changes to home
131cd ..                         # changes to the parent directory
132cd <dirname>                  # changes directory
133cp -r <dir1> <dir2>           # copy <dir1> into <dir2> including sub-directories
134pwd                           # tells you where you currently are
135cd ~                          # changes to home.
136cd -                          # changes to previous working directory
137
138##############################################################################
139# SSH, SYSTEM INFO & NETWORK COMMANDS
140##############################################################################
141
142
143ssh user@host            # connects to host as user
144ssh -p <port> user@host  # connects to host on specified port as user
145ssh-copy-id user@host    # adds your ssh key to host for user to enable a keyed or passwordless login
146
147whoami                   # returns your username
148passwd                   # lets you change your password
149quota -v                 # shows what your disk quota is
150date                     # shows the current date and time
151cal                      # shows the month's calendar
152uptime                   # shows current uptime
153w                        # displays whois online
154finger <user>            # displays information about user
155uname -a                 # shows kernel information
156man <command>            # shows the manual for specified command
157df                       # shows disk usage
158du <filename>            # shows the disk usage of the files and directories in filename (du -s give only a total)
159last <yourUsername>      # lists your last logins
160ps -u yourusername       # lists your processes
161kill <PID>               # kills the processes with the ID you gave
162killall <processname>    # kill all processes with the name
163top                      # displays your currently active processes
164lsof                     # lists open files
165bg                       # lists stopped or background jobs ; resume a stopped job in the background
166fg                       # brings the most recent job in the foreground
167fg <job>                 # brings job to the foreground
168
169ping <host>              # pings host and outputs results
170whois <domain>           # gets whois information for domain
171dig <domain>             # gets DNS information for domain
172dig -x <host>            # reverses lookup host
173wget <file>              # downloads file
174
175time <command>             # report time consumed by command execution
176
177
178##############################################################################
179# VARIABLES
180##############################################################################
181
182
183varname=value                # defines a variable
184varname=value command        # defines a variable to be in the environment of a particular subprocess
185echo $varname                # checks a variable's value
186echo $$                      # prints process ID of the current shell
187echo $!                      # prints process ID of the most recently invoked background job
188echo $?                      # displays the exit status of the last command
189read <varname>               # reads a string from the input and assigns it to a variable
190read -p "prompt" <varname>   # same as above but outputs a prompt to ask user for value 
191column -t <filename>         # display info in pretty columns (often used with pipe)
192let <varname> = <equation>   # performs mathematical calculation using operators like +, -, *, /, %
193export VARNAME=value         # defines an environment variable (will be available in subprocesses)
194
195array[0]=valA                # how to define an array
196array[1]=valB
197array[2]=valC
198array=([2]=valC [0]=valA [1]=valB)  # another way
199array=(valA valB valC)              # and another
200
201${array[i]}                  # displays array's value for this index. If no index is supplied, array element 0 is assumed
202${#array[i]}                 # to find out the length of any element in the array
203${#array[@]}                 # to find out how many values there are in the array
204
205declare -a                   # the variables are treated as arrays
206declare -f                   # uses function names only
207declare -F                   # displays function names without definitions
208declare -i                   # the variables are treated as integers
209declare -r                   # makes the variables read-only
210declare -x                   # marks the variables for export via the environment
211
212${varname:-word}             # if varname exists and isn't null, return its value; otherwise return word
213${varname:word}              # if varname exists and isn't null, return its value; otherwise return word
214${varname:=word}             # if varname exists and isn't null, return its value; otherwise set it word and then return its value
215${varname:?message}          # if varname exists and isn't null, return its value; otherwise print varname, followed by message and abort the current command or script
216${varname:+word}             # if varname exists and isn't null, return word; otherwise return null
217${varname:offset:length}     # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
218
219${variable#pattern}          # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
220${variable##pattern}         # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
221${variable%pattern}          # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
222${variable%%pattern}         # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
223${variable/pattern/string}   # the longest match to pattern in variable is replaced by string. Only the first match is replaced
224${variable//pattern/string}  # the longest match to pattern in variable is replaced by string. All matches are replaced
225
226${#varname}                  # returns the length of the value of the variable as a character string
227
228*(patternlist)               # matches zero or more occurrences of the given patterns
229+(patternlist)               # matches one or more occurrences of the given patterns
230?(patternlist)               # matches zero or one occurrence of the given patterns
231@(patternlist)               # matches exactly one of the given patterns
232!(patternlist)               # matches anything except one of the given patterns
233
234$(UNIX command)              # command substitution: runs the command and returns standard output
235
236
237##############################################################################
238# FUNCTIONS
239##############################################################################
240
241
242# The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
243# $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.
244
245
246function functname() {
247  shell commands
248}
249
250unset -f functname  # deletes a function definition
251declare -f          # displays all defined functions in your login session
252
253
254##############################################################################
255# FLOW CONTROLS
256##############################################################################
257
258
259statement1 && statement2  # and operator
260statement1 || statement2  # or operator
261
262-a                        # and operator inside a test conditional expression
263-o                        # or operator inside a test conditional expression
264
265# STRINGS
266
267str1 == str2               # str1 matches str2
268str1 != str2               # str1 does not match str2
269str1 < str2                # str1 is less than str2 (alphabetically)
270str1 > str2                # str1 is greater than str2 (alphabetically)
271str1 \> str2               # str1 is sorted after str2
272str1 \< str2               # str1 is sorted before str2
273-n str1                    # str1 is not null (has length greater than 0)
274-z str1                    # str1 is null (has length 0)
275
276# FILES
277
278-a file                   # file exists or its compilation is successful
279-d file                   # file exists and is a directory
280-e file                   # file exists; same -a
281-f file                   # file exists and is a regular file (i.e., not a directory or other special type of file)
282-r file                   # you have read permission
283-s file                   # file exists and is not empty
284-w file                   # your have write permission
285-x file                   # you have execute permission on file, or directory search permission if it is a directory
286-N file                   # file was modified since it was last read
287-O file                   # you own file
288-G file                   # file's group ID matches yours (or one of yours, if you are in multiple groups)
289file1 -nt file2           # file1 is newer than file2
290file1 -ot file2           # file1 is older than file2
291
292# NUMBERS
293
294-lt                       # less than
295-le                       # less than or equal
296-eq                       # equal
297-ge                       # greater than or equal
298-gt                       # greater than
299-ne                       # not equal
300
301if condition
302then
303  statements
304[elif condition
305  then statements...]
306[else
307  statements]
308fi
309
310for x in {1..10}
311do
312  statements
313done
314
315for name [in list]
316do
317  statements that can use $name
318done
319
320for (( initialisation ; ending condition ; update ))
321do
322  statements...
323done
324
325case expression in
326  pattern1 )
327    statements ;;
328  pattern2 )
329    statements ;;
330esac
331
332select name [in list]
333do
334  statements that can use $name
335done
336
337while condition; do
338  statements
339done
340
341until condition; do
342  statements
343done
344
345##############################################################################
346# COMMAND-LINE PROCESSING CYCLE
347##############################################################################
348
349
350# The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
351# There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.
352
353command  # removes alias and function lookup. Only built-ins and commands found in the search path are executed
354builtin  # looks up only built-in commands, ignoring functions and commands found in PATH
355enable   # enables and disables shell built-ins
356
357eval     # takes arguments and run them through the command-line processing steps all over again
358
359
360##############################################################################
361# INPUT/OUTPUT REDIRECTORS
362##############################################################################
363
364
365cmd1|cmd2  # pipe; takes standard output of cmd1 as standard input to cmd2
366< file     # takes standard input from file
367> file     # directs standard output to file
368>> file    # directs standard output to file; append to file if it already exists
369>|file     # forces standard output to file even if noclobber is set
370n>|file    # forces output to file from file descriptor n even if noclobber is set
371<> file    # uses file as both standard input and standard output
372n<>file    # uses file as both input and output for file descriptor n
373n>file     # directs file descriptor n to file
374n<file     # takes file descriptor n from file
375n>>file    # directs file description n to file; append to file if it already exists
376n>&        # duplicates standard output to file descriptor n
377n<&        # duplicates standard input from file descriptor n
378n>&m       # file descriptor n is made to be a copy of the output file descriptor
379n<&m       # file descriptor n is made to be a copy of the input file descriptor
380&>file     # directs standard output and standard error to file
381<&-        # closes the standard input
382>&-        # closes the standard output
383n>&-       # closes the ouput from file descriptor n
384n<&-       # closes the input from file descripor n
385
386|tee <file># output command to both terminal and a file (-a to append to file)
387
388
389##############################################################################
390# PROCESS HANDLING
391##############################################################################
392
393
394# To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
395# This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
396# Of course, to interrupt a job, type CTRL+C.
397
398myCommand &  # runs job in the background and prompts back the shell
399
400jobs         # lists all jobs (use with -l to see associated PID)
401
402fg           # brings a background job into the foreground
403fg %+        # brings most recently invoked background job
404fg %-        # brings second most recently invoked background job
405fg %N        # brings job number N
406fg %string   # brings job whose command begins with string
407fg %?string  # brings job whose command contains string
408
409kill -l               # returns a list of all signals on the system, by name and number
410kill PID              # terminates process with specified PID
411kill -s SIGKILL 4500  # sends a signal to force or terminate the process
412kill -15 913          # Ending PID 913 process with signal 15 (TERM)
413kill %1               # Where %1 is the number of job as read from 'jobs' command.
414
415ps           # prints a line of information about the current running login shell and any processes running under it
416ps -a        # selects all processes with a tty except session leaders
417
418trap cmd sig1 sig2  # executes a command when a signal is received by the script
419trap "" sig1 sig2   # ignores that signals
420trap - sig1 sig2    # resets the action taken when the signal is received to the default
421
422disown <PID|JID>    # removes the process from the list of jobs
423
424wait                # waits until all background jobs have finished
425sleep <number>      # wait # of seconds before continuing
426
427pv                  # display progress bar for data handling commands. often used with pipe like |pv
428yes                 # give yes response everytime an input is requested from script/process
429
430
431##############################################################################
432# TIPS & TRICKS
433##############################################################################
434
435
436# set an alias
437cd; nano .bash_profile
438> alias gentlenode='ssh admin@gentlenode.com -p 3404'  # add your alias in .bash_profile
439
440# to quickly go to a specific directory
441cd; nano .bashrc
442> shopt -s cdable_vars
443> export websites="/Users/mac/Documents/websites"
444
445source .bashrc
446cd $websites
447
448
449##############################################################################
450# DEBUGGING SHELL PROGRAMS
451##############################################################################
452
453
454bash -n scriptname  # don't run commands; check for syntax errors only
455set -o noexec       # alternative (set option in script)
456
457bash -v scriptname  # echo commands before running them
458set -o verbose      # alternative (set option in script)
459
460bash -x scriptname  # echo commands after command-line processing
461set -o xtrace       # alternative (set option in script)
462
463trap 'echo $varname' EXIT  # useful when you want to print out the values of variables at the point that your script exits
464
465function errtrap {
466  es=$?
467  echo "ERROR line $1: Command exited with status $es."
468}
469
470trap 'errtrap $LINENO' ERR  # is run whenever a command in the surrounding script or function exits with non-zero status
471
472function dbgtrap {
473  echo "badvar is $badvar"
474}
475
476trap dbgtrap DEBUG  # causes the trap code to be executed before every statement in a function or script
477# ...section of code in which the problem occurs...
478trap - DEBUG  # turn off the DEBUG trap
479
480function returntrap {
481  echo "A return occurred"
482}
483
484trap returntrap RETURN  # is executed each time a shell function or a script executed with the . or source commands finishes executing
485
486##############################################################################
487# COLORS AND BACKGROUNDS 
488##############################################################################
489# note: \e or \x1B also work instead of \033 
490# Reset
491Color_Off='\033[0m' # Text Reset
492
493# Regular Colors
494Black='\033[0;30m'  # Black
495Red='\033[0;31m'    # Red
496Green='\033[0;32m'  # Green
497Yellow='\033[0;33m' # Yellow
498Blue='\033[0;34m'   # Blue
499Purple='\033[0;35m' # Purple
500Cyan='\033[0;36m'   # Cyan
501White='\033[0;97m'  # White
502
503# Additional colors
504LGrey='\033[0;37m'  # Ligth Gray
505DGrey='\033[0;90m'  # Dark Gray
506LRed='\033[0;91m'   # Ligth Red
507LGreen='\033[0;92m' # Ligth Green
508LYellow='\033[0;93m'# Ligth Yellow
509LBlue='\033[0;94m'  # Ligth Blue
510LPurple='\033[0;95m'# Light Purple
511LCyan='\033[0;96m'  # Ligth Cyan
512
513
514# Bold
515BBlack='\033[1;30m' # Black
516BRed='\033[1;31m'   # Red
517BGreen='\033[1;32m' # Green
518BYellow='\033[1;33m'# Yellow
519BBlue='\033[1;34m'  # Blue
520BPurple='\033[1;35m'# Purple
521BCyan='\033[1;36m'  # Cyan
522BWhite='\033[1;37m' # White
523
524# Underline
525UBlack='\033[4;30m' # Black
526URed='\033[4;31m'   # Red
527UGreen='\033[4;32m' # Green
528UYellow='\033[4;33m'# Yellow
529UBlue='\033[4;34m'  # Blue
530UPurple='\033[4;35m'# Purple
531UCyan='\033[4;36m'  # Cyan
532UWhite='\033[4;37m' # White
533
534# Background
535On_Black='\033[40m' # Black
536On_Red='\033[41m'   # Red
537On_Green='\033[42m' # Green
538On_Yellow='\033[43m'# Yellow
539On_Blue='\033[44m'  # Blue
540On_Purple='\033[45m'# Purple
541On_Cyan='\033[46m'  # Cyan
542On_White='\033[47m' # White
543
544# Example of usage
545echo -e "${Green}This is GREEN text${Color_Off} and normal text"
546echo -e "${Red}${On_White}This is Red test on White background${Color_Off}" 
547# option -e is mandatory, it enable interpretation of backslash escapes
548printf "${Red} This is red \n"

Cheat Sheet for C
Mongodb Error Solutions