Loading

Bash - Tips

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

Comments