GonMAX

Bash Cheatsheet

Nov 25th, 2019
219
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 19.99 KB | None | 0 0
  1. #!/bin/bash
  2. ##############################################################################
  3. # SHORTCUTS and HISTORY
  4. ##############################################################################
  5.  
  6. CTRL+A  # move to beginning of line
  7. CTRL+B  # moves backward one character
  8. CTRL+C  # halts the current command
  9. CTRL+D  # deletes one character backward or logs out of current session, similar to exit
  10. CTRL+E  # moves to end of line
  11. CTRL+F  # moves forward one character
  12. CTRL+G  # aborts the current editing command and ring the terminal bell
  13. CTRL+H  # deletes one character under cursor (same as DELETE)
  14. CTRL+J  # same as RETURN
  15. CTRL+K  # deletes (kill) forward to end of line
  16. CTRL+L  # clears screen and redisplay the line
  17. CTRL+M  # same as RETURN
  18. CTRL+N  # next line in command history
  19. CTRL+O  # same as RETURN, then displays next line in history file
  20. CTRL+P  # previous line in command history
  21. CTRL+R  # searches backward
  22. CTRL+S  # searches forward
  23. CTRL+T  # transposes two characters
  24. CTRL+U  # kills backward from point to the beginning of line
  25. CTRL+V  # makes the next character typed verbatim
  26. CTRL+W  # kills the word behind the cursor
  27. CTRL+X  # lists the possible filename completions of the current word
  28. CTRL+Y  # retrieves (yank) last item killed
  29. CTRL+Z  # stops the current command, resume with fg in the foreground or bg in the background
  30.  
  31. ALT+B   # moves backward one word
  32. ALT+D   # deletes next word
  33. ALT+F   # moves forward one word
  34. ALT+H   # deletes one character backward
  35.  
  36. BACKSPACE  # deletes one character backward
  37. DELETE     # deletes one character under cursor
  38.  
  39. history   # shows command line history
  40. !!        # repeats the last command
  41. !<n>      # refers to command line 'n'
  42. !<string> # refers to command starting with 'string'
  43.  
  44. exit      # logs out of current session
  45.  
  46.  
  47. ##############################################################################
  48. # BASH BASICS
  49. ##############################################################################
  50.  
  51. env                 # displays all environment variables
  52.  
  53. echo $SHELL         # displays the shell you're using
  54. echo $BASH_VERSION  # displays bash version
  55.  
  56. bash                # if you want to use bash (type exit to go back to your previously opened shell)
  57. whereis bash        # locates the binary, source and manual-page for a command
  58. which bash          # finds out which program is executed as 'bash' (default: /bin/bash, can change across environments)
  59.  
  60. clear               # clears content on window (hide displayed lines)
  61.  
  62.  
  63. ##############################################################################
  64. # FILE COMMANDS
  65. ##############################################################################
  66.  
  67.  
  68. ls                            # lists your files in current directory, ls <dir> to print files in a specific directory
  69. ls -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
  70. ls -a                         # lists all files, including hidden files (name beginning with '.')
  71. ln -s <filename> <link>       # creates symbolic link to file
  72. touch <filename>              # creates or updates (edit) your file
  73. cat <filename>                # prints file raw content (will not be interpreted)
  74. any_command > <filename>      # '>' is used to perform redirections, it will set any_command's stdout to file instead of "real stdout" (generally /dev/stdout)
  75. more <filename>               # shows the first part of a file (move with space and type q to quit)
  76. head <filename>               # outputs the first lines of file (default: 10 lines)
  77. tail <filename>               # outputs the last lines of file (useful with -f option) (default: 10 lines)
  78. vim <filename>                # opens a file in VIM (VI iMproved) text editor, will create it if it doesn't exist
  79. mv <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))
  80. cp <filename1> <dest>         # copies a file
  81. rm <filename>                 # removes a file
  82. diff <filename1> <filename2>  # compares files, and shows where they differ
  83. wc <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
  84. chmod -options <filename>     # lets you change the read, write, and execute permissions on your files (more infos: SUID, GUID)
  85. gzip <filename>               # compresses files using gzip algorithm
  86. gunzip <filename>             # uncompresses files compressed by gzip
  87. gzcat <filename>              # lets you look at gzipped file without actually having to gunzip it
  88. lpr <filename>                # prints the file
  89. lpq                           # checks out the printer queue
  90. lprm <jobnumber>              # removes something from the printer queue
  91. genscript                     # converts plain text files into postscript for printing and gives you some options for formatting
  92. dvips <filename>              # prints .dvi files (i.e. files produced by LaTeX)
  93. grep <pattern> <filenames>    # looks for the string in the files
  94. grep -r <pattern> <dir>       # search recursively for pattern in directory
  95.  
  96.  
  97. ##############################################################################
  98. # DIRECTORY COMMANDS
  99. ##############################################################################
  100.  
  101.  
  102. mkdir <dirname>  # makes a new directory
  103. cd               # changes to home
  104. cd <dirname>     # changes directory
  105. pwd              # tells you where you currently are
  106.  
  107.  
  108. ##############################################################################
  109. # SSH, SYSTEM INFO & NETWORK COMMANDS
  110. ##############################################################################
  111.  
  112.  
  113. ssh user@host            # connects to host as user
  114. ssh -p <port> user@host  # connects to host on specified port as user
  115. ssh-copy-id user@host    # adds your ssh key to host for user to enable a keyed or passwordless login
  116.  
  117. whoami                   # returns your username
  118. passwd                   # lets you change your password
  119. quota -v                 # shows what your disk quota is
  120. date                     # shows the current date and time
  121. cal                      # shows the month's calendar
  122. uptime                   # shows current uptime
  123. w                        # displays whois online
  124. finger <user>            # displays information about user
  125. uname -a                 # shows kernel information
  126. man <command>            # shows the manual for specified command
  127. df                       # shows disk usage
  128. du <filename>            # shows the disk usage of the files and directories in filename (du -s give only a total)
  129. last <yourUsername>      # lists your last logins
  130. ps -u yourusername       # lists your processes
  131. kill <PID>               # kills the processes with the ID you gave
  132. killall <processname>    # kill all processes with the name
  133. top                      # displays your currently active processes
  134. bg                       # lists stopped or background jobs ; resume a stopped job in the background
  135. fg                       # brings the most recent job in the foreground
  136. fg <job>                 # brings job to the foreground
  137.  
  138. ping <host>              # pings host and outputs results
  139. whois <domain>           # gets whois information for domain
  140. dig <domain>             # gets DNS information for domain
  141. dig -x <host>            # reverses lookup host
  142. wget <file>              # downloads file
  143.  
  144.  
  145. ##############################################################################
  146. # VARIABLES
  147. ##############################################################################
  148.  
  149.  
  150. varname=value                # defines a variable
  151. varname=value command        # defines a variable to be in the environment of a particular subprocess
  152. echo $varname                # checks a variable's value
  153. echo $$                      # prints process ID of the current shell
  154. echo $!                      # prints process ID of the most recently invoked background job
  155. echo $?                      # displays the exit status of the last command
  156. export VARNAME=value         # defines an environment variable (will be available in subprocesses)
  157.  
  158. array[0]=valA                # how to define an array
  159. array[1]=valB
  160. array[2]=valC
  161. array=([2]=valC [0]=valA [1]=valB)  # another way
  162. array=(valA valB valC)              # and another
  163.  
  164. ${array[i]}                  # displays array's value for this index. If no index is supplied, array element 0 is assumed
  165. ${#array[i]}                 # to find out the length of any element in the array
  166. ${#array[@]}                 # to find out how many values there are in the array
  167.  
  168. declare -a                   # the variables are treaded as arrays
  169. declare -f                   # uses function names only
  170. declare -F                   # displays function names without definitions
  171. declare -i                   # the variables are treaded as integers
  172. declare -r                   # makes the variables read-only
  173. declare -x                   # marks the variables for export via the environment
  174.  
  175. ${varname:-word}             # if varname exists and isn't null, return its value; otherwise return word
  176. ${varname:=word}             # if varname exists and isn't null, return its value; otherwise set it word and then return its value
  177. ${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
  178. ${varname:+word}             # if varname exists and isn't null, return word; otherwise return null
  179. ${varname:offset:length}     # performs substring expansion. It returns the substring of $varname starting at offset and up to length characters
  180.  
  181. ${variable#pattern}          # if the pattern matches the beginning of the variable's value, delete the shortest part that matches and return the rest
  182. ${variable##pattern}         # if the pattern matches the beginning of the variable's value, delete the longest part that matches and return the rest
  183. ${variable%pattern}          # if the pattern matches the end of the variable's value, delete the shortest part that matches and return the rest
  184. ${variable%%pattern}         # if the pattern matches the end of the variable's value, delete the longest part that matches and return the rest
  185. ${variable/pattern/string}   # the longest match to pattern in variable is replaced by string. Only the first match is replaced
  186. ${variable//pattern/string}  # the longest match to pattern in variable is replaced by string. All matches are replaced
  187.  
  188. ${#varname}                  # returns the length of the value of the variable as a character string
  189.  
  190. *(patternlist)               # matches zero or more occurrences of the given patterns
  191. +(patternlist)               # matches one or more occurrences of the given patterns
  192. ?(patternlist)               # matches zero or one occurrence of the given patterns
  193. @(patternlist)               # matches exactly one of the given patterns
  194. !(patternlist)               # matches anything except one of the given patterns
  195.  
  196. $(UNIX command)              # command substitution: runs the command and returns standard output
  197.  
  198.  
  199. ##############################################################################
  200. # FUNCTIONS
  201. ##############################################################################
  202.  
  203.  
  204. # The function refers to passed arguments by position (as if they were positional parameters), that is, $1, $2, and so forth.
  205. # $@ is equal to "$1" "$2"... "$N", where N is the number of positional parameters. $# holds the number of positional parameters.
  206.  
  207.  
  208. function functname() {
  209.   shell commands
  210. }
  211.  
  212. unset -f functname  # deletes a function definition
  213. declare -f          # displays all defined functions in your login session
  214.  
  215.  
  216. ##############################################################################
  217. # FLOW CONTROLS
  218. ##############################################################################
  219.  
  220.  
  221. statement1 && statement2  # and operator
  222. statement1 || statement2  # or operator
  223.  
  224. -a                        # and operator inside a test conditional expression
  225. -o                        # or operator inside a test conditional expression
  226.  
  227. # STRINGS
  228.  
  229. str1 == str2               # str1 matches str2
  230. str1 != str2               # str1 does not match str2
  231. str1 < str2                # str1 is less than str2 (alphabetically)
  232. str1 > str2                # str1 is greater than str2 (alphabetically)
  233. -n str1                    # str1 is not null (has length greater than 0)
  234. -z str1                    # str1 is null (has length 0)
  235.  
  236. # FILES
  237.  
  238. -a file                   # file exists
  239. -d file                   # file exists and is a directory
  240. -e file                   # file exists; same -a
  241. -f file                   # file exists and is a regular file (i.e., not a directory or other special type of file)
  242. -r file                   # you have read permission
  243. -s file                   # file exists and is not empty
  244. -w file                   # your have write permission
  245. -x file                   # you have execute permission on file, or directory search permission if it is a directory
  246. -N file                   # file was modified since it was last read
  247. -O file                   # you own file
  248. -G file                   # file's group ID matches yours (or one of yours, if you are in multiple groups)
  249. file1 -nt file2           # file1 is newer than file2
  250. file1 -ot file2           # file1 is older than file2
  251.  
  252. # NUMBERS
  253.  
  254. -lt                       # less than
  255. -le                       # less than or equal
  256. -eq                       # equal
  257. -ge                       # greater than or equal
  258. -gt                       # greater than
  259. -ne                       # not equal
  260.  
  261. if condition
  262. then
  263.   statements
  264. [elif condition
  265.   then statements...]
  266. [else
  267.   statements]
  268. fi
  269.  
  270. for x in {1..10}
  271. do
  272.   statements
  273. done
  274.  
  275. for name [in list]
  276. do
  277.   statements that can use $name
  278. done
  279.  
  280. for (( initialisation ; ending condition ; update ))
  281. do
  282.   statements...
  283. done
  284.  
  285. case expression in
  286.   pattern1 )
  287.     statements ;;
  288.   pattern2 )
  289.     statements ;;
  290. esac
  291.  
  292. select name [in list]
  293. do
  294.   statements that can use $name
  295. done
  296.  
  297. while condition; do
  298.   statements
  299. done
  300.  
  301. until condition; do
  302.   statements
  303. done
  304.  
  305. ##############################################################################
  306. # COMMAND-LINE PROCESSING CYCLE
  307. ##############################################################################
  308.  
  309.  
  310. # The default order for command lookup is functions, followed by built-ins, with scripts and executables last.
  311. # There are three built-ins that you can use to override this order: `command`, `builtin` and `enable`.
  312.  
  313. command  # removes alias and function lookup. Only built-ins and commands found in the search path are executed
  314. builtin  # looks up only built-in commands, ignoring functions and commands found in PATH
  315. enable   # enables and disables shell built-ins
  316.  
  317. eval     # takes arguments and run them through the command-line processing steps all over again
  318.  
  319.  
  320. ##############################################################################
  321. # INPUT/OUTPUT REDIRECTORS
  322. ##############################################################################
  323.  
  324.  
  325. cmd1|cmd2  # pipe; takes standard output of cmd1 as standard input to cmd2
  326. < file     # takes standard input from file
  327. > file     # directs standard output to file
  328. >> file    # directs standard output to file; append to file if it already exists
  329. >|file     # forces standard output to file even if noclobber is set
  330. n>|file    # forces output to file from file descriptor n even if noclobber is set
  331. <> file    # uses file as both standard input and standard output
  332. n<>file    # uses file as both input and output for file descriptor n
  333. n>file     # directs file descriptor n to file
  334. n<file     # takes file descriptor n from file
  335. n>>file    # directs file description n to file; append to file if it already exists
  336. n>&        # duplicates standard output to file descriptor n
  337. n<&        # duplicates standard input from file descriptor n
  338. n>&m       # file descriptor n is made to be a copy of the output file descriptor
  339. n<&m       # file descriptor n is made to be a copy of the input file descriptor
  340. &>file     # directs standard output and standard error to file
  341. <&-        # closes the standard input
  342. >&-        # closes the standard output
  343. n>&-       # closes the ouput from file descriptor n
  344. n<&-       # closes the input from file descripor n
  345.  
  346.  
  347. ##############################################################################
  348. # PROCESS HANDLING
  349. ##############################################################################
  350.  
  351.  
  352. # To suspend a job, type CTRL+Z while it is running. You can also suspend a job with CTRL+Y.
  353. # This is slightly different from CTRL+Z in that the process is only stopped when it attempts to read input from terminal.
  354. # Of course, to interrupt a job, type CTRL+C.
  355.  
  356. myCommand &  # runs job in the background and prompts back the shell
  357.  
  358. jobs         # lists all jobs (use with -l to see associated PID)
  359.  
  360. fg           # brings a background job into the foreground
  361. fg %+        # brings most recently invoked background job
  362. fg %-        # brings second most recently invoked background job
  363. fg %N        # brings job number N
  364. fg %string   # brings job whose command begins with string
  365. fg %?string  # brings job whose command contains string
  366.  
  367. kill -l               # returns a list of all signals on the system, by name and number
  368. kill PID              # terminates process with specified PID
  369. kill -s SIGKILL 4500  # sends a signal to force or terminate the process
  370. kill -15 913          # Ending PID 913 process with signal 15 (TERM)
  371.  
  372. ps           # prints a line of information about the current running login shell and any processes running under it
  373. ps -a        # selects all processes with a tty except session leaders
  374.  
  375. trap cmd sig1 sig2  # executes a command when a signal is received by the script
  376. trap "" sig1 sig2   # ignores that signals
  377. trap - sig1 sig2    # resets the action taken when the signal is received to the default
  378.  
  379. disown <PID|JID>    # removes the process from the list of jobs
  380.  
  381. wait                # waits until all background jobs have finished
  382.  
  383.  
  384. ##############################################################################
  385. # TIPS & TRICKS
  386. ##############################################################################
  387.  
  388.  
  389. # set an alias
  390. cd; nano .bash_profile
  391. > alias gentlenode='ssh [email protected] -p 3404'  # add your alias in .bash_profile
  392.  
  393. # to quickly go to a specific directory
  394. cd; nano .bashrc
  395. > shopt -s cdable_vars
  396. > export websites="/Users/mac/Documents/websites"
  397.  
  398. source .bashrc
  399. cd $websites
  400.  
  401.  
  402. ##############################################################################
  403. # DEBUGGING SHELL PROGRAMS
  404. ##############################################################################
  405.  
  406.  
  407. bash -n scriptname  # don't run commands; check for syntax errors only
  408. set -o noexec       # alternative (set option in script)
  409.  
  410. bash -v scriptname  # echo commands before running them
  411. set -o verbose      # alternative (set option in script)
  412.  
  413. bash -x scriptname  # echo commands after command-line processing
  414. set -o xtrace       # alternative (set option in script)
  415.  
  416. trap 'echo $varname' EXIT  # useful when you want to print out the values of variables at the point that your script exits
  417.  
  418. function errtrap {
  419.   es=$?
  420.   echo "ERROR line $1: Command exited with status $es."
  421. }
  422.  
  423. trap 'errtrap $LINENO' ERR  # is run whenever a command in the surrounding script or function exits with non-zero status
  424.  
  425. function dbgtrap {
  426.   echo "badvar is $badvar"
  427. }
  428.  
  429. trap dbgtrap DEBUG  # causes the trap code to be executed before every statement in a function or script
  430. # ...section of code in which the problem occurs...
  431. trap - DEBUG  # turn off the DEBUG trap
  432.  
  433. function returntrap {
  434.   echo "A return occurred"
  435. }
  436.  
  437. trap returntrap RETURN  # is executed each time a shell function or a script executed with the . or source commands finishes executing
Advertisement
Add Comment
Please, Sign In to add comment