Guest User

Untitled

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