Advertisement
Guest User

Untitled

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