<<

1 of 4 ########################################### # 1.1. Commands. # Name: CheatSheet # # # # A little overlook of the Bash basics # # lists your files # # ls -l # lists your files in 'long format' # Usage: A Helpful Guide # ls -a # lists all files, including hidden files # # -s # creates symbolic to file # Author: J. Le Coupanec # # creates or updates your file # Date: 2014/11/04 # > # places standard input into file # Edited: 2015/8/18 – Michael Stobb # # shows the first part of a file (q to quit) ########################################### # outputs the first 10 lines of file # outputs the last 10 lines of file (-f too) # 0. Shortcuts. emacs # lets you create and edit a file # moves a file # copies a file CTRL+A # to beginning of line # removes a file CTRL+B # moves backward one character # compares files, and shows where differ CTRL+C # halts the current command # tells you how many lines, words there are CTRL+D # deletes one character backward or logs out of current session -options # lets you change the permissions on files CTRL+E # moves to end of line gzip # compresses files CTRL+F # moves forward one character gunzip # uncompresses files compressed by gzip CTRL+G # aborts the current editing command and ring the terminal bell gzcat # lets you look gzipped files CTRL+J # same as RETURN lpr # print the file CTRL+K # deletes () forward to end of line lpq # check out the printer queue CTRL+L # clears screen and redisplay the line lprm # remove something from the printer queue CTRL+M # same as RETURN # looks for the string in the files CTRL+N # next line in command grep -r

# search recursively for pattern in CTRL+O # same as RETURN, then displays next line in history file CTRL+P # previous line in command history CTRL+R # searches backward # 1.2. Directory Commands. CTRL+S # searches forward CTRL+T # transposes two characters CTRL+U # kills backward from point to the beginning of line # makes a new directory CTRL+V # makes the next character typed verbatim # changes to home CTRL+ # kills the word behind the cursor cd # changes directory CTRL+X # lists the possible filename completefions of the current word # tells you where you currently are CTRL+Y # retrieves (yank) last item killed CTRL+Z # stops the current command, resume with fg in the foreground or bg in the background # 1.3. SSH, System & Network Commands. DELETE # deletes one character backward !! # repeats the last command # logs out of current session ssh user@ # connects to host as user ssh -p user@host # connects to host on specified port as user ssh--id user@host # adds your ssh key to host for user to enable a # 1. Bash Basics. keyed or passwordless login

# returns your username export # displays all environment variables # lets you change your password quota -v # shows what your disk quota is $ # displays the shell you're using date # shows the current date and echo $BASH_VERSION # displays bash version # shows the month's calendar # shows current uptime bash # if you want to use bash ( exit to go back to w # displays whois online your normal shell) finger # displays information about user bash # finds out where bash is on your system -a # shows kernel information man # shows the manual for specified command # clears content on window (hide displayed lines) # shows disk usage # shows the disk usage of the files and 2 of 4 directories in filename (du -s give only a total) last # lists your last logins ${#varname} # returns the length of the value of the -u yourusername # lists your processes variable as a character string kill # kills (ends) the processes with the ID you gave # kill all processes with the name *(patternlist) # matches zero or more occurences of the # displays your currently active processes given patterns bg # lists stopped or background jobs +(patternlist) # matches one or more occurences of the given fg # brings the recent job in the foreground patterns fg # brings job to the foreground ?(patternlist) # matches zero or one occurence of the given patterns ping # pings host and outputs results @(patternlist) # matches exactly one of the given patterns whois # gets whois information for domain !(patternlist) # matches anything except one of the given # gets DNS information for domain patterns dig -x # reverses lookup host $(UNIX command) # command substitution: runs the command and wget # downloads file returns standard output

# 2. Basic Shell Programming. # 2.2. Functions.

# 2.1. Variables. # The function refers to passed arguments by position (as if they were # positional parameters), that is, $1, $2, and so forth. $@ is equal to # "$1" "$2"... "$N", where N is the number of positional parameters. $# varname=value # defines a variable # holds the number of positional parameters. varname=value command # defines a variable to be in the environment echo $varname # checks a variable's value functname() { echo $$ # prints process ID of the current shell shell commands echo $! # prints process ID of the most recent job } echo $? # displays the exit status of last command export VARNAME=value # defines an unset -f functname # deletes a function definition declare -f # displays all defined functions in your login session array[0] = val # several ways to define an array array[1] = val array[2] = val # 2.3. Flow Control. array=([2]=val [0]=val [1]=val) array(val val val) statement1 && statement2 # and operator ${array[i]} # displays array's value for this index statement1 || statement2 # or operator ${#array[i]} # to out the length of any element ${#array[@]} # to find out how many values there are -a # and operator inside a conditional -o # or operator inside a test conditional declare -a # the variables are treaded as arrays declare -f # uses funtion names only str1=str2 # str1 matches str2 declare -F # displays function names without definitions str1!=str2 # str1 does not match str2 declare -i # the variables are treaded as integers str1str2 # str1 is greater than str2 declare -x # marks the variables for export via the -n str1 # str1 is not null (has length greater than 0) environment -z str1 # str1 is null (has length 0)

${varname:-word} # if varname exists and isn't null, return -a file # file exists its value; otherwise return word -d file # file exists and is a directory ${varname:=word} # if varname exists and isn't null, return -e file # file exists; same -a its value; otherwise set it word and then return its value -f file # file exists and is a regular file ${varname:?message} # if varname exists and isn't null, return -r file # you have read permission its value; otherwise print varname, followed by message and abort -r file # file exists and is not empty the current command or script -w file # your have permission ${varname:+word} # if varname exists and isn't null, return -x file # you have execute permission on file word; otherwise return null -N file # file was modified since it was last read ${varname:offset:length} # performs substring expansion -O file # you own file 3 of 4 -G file # file's group ID matches yours # 3. Command-Line Processing Cycle. file1 -nt file2 # file1 is newer than file2 file1 -ot file2 # file1 is older than file2 # The default order for command lookup is functions, followed by built- -lt # than # ins, with scripts and executables last. There are three built-ins that -le # less than or equal # you can use to override this order:`command`, `builtin` and `enable`. -eq # equal -ge # greater than or equal command # removes and function lookup. Only built-ins and commands -gt # greater than found in the search are executed -ne # not equal builtin # looks up only built-in commands, ignoring functions and commands found in PATH if condition enable # enables and disables shell built-ins then statements eval # takes arguments and run them through the command-line [elif condition processing steps all over again then statements...] [else statements] fi # 4. Input/Output Redirectors. for x := 1 to 10 do begin cmd1|cmd2 # pipe; takes standard output of cmd1 as standard input to cmd2 statements > file # directs standard output to file end < file # takes standard input from file >> file # directs standard output to file; append to file if it exists for name [in list] &>file # directs standard output and standard error to file do <&- # closes the standard input statements that can use $name >&- # closes the standard output done for (( initialisation ; ending condition ; update )) # 5. Process Handling. do statements... done # To suspend a job, type CTRL+Z while it is running. You can also suspend # a job with CTRL+Y. This is slightly different from CTRL+Z in that the case expression in # process is only stopped when it attempts to read input from terminal. pattern1 ) # Of course, to interrupt a job, type CTRL+C. statements ;; pattern2 ) myCommand & # runs job in the background and prompts back the shell statements ;; ... jobs # lists all jobs (use with -l to see associated PID) esac fg # brings a background job into the foreground select name [in list] fg %+ # brings most recently invoked background job do fg %- # brings second most recently invoked background job statements that can use $name fg %N # brings job number N done fg %string # brings job whose command begins with string fg %?string # brings job whose command contains string while condition; do statements kill -l # returns a list of all signals on the system done kill PID # terminates process with specified PID until condition; do statements ps # prints a line of information about the current running done login shell and any processes running under it ps -a # selects all processes with a except session leaders

trap cmd sig1 sig2 # executes a command when a is received by the 4 of 4 script trap - DEBUG # turn off the DEBUG trap trap "" sig1 sig2 # ignores that signals trap - sig1 sig2 # resets the action taken when the signal is received function returntrap { to the default echo "A return occured" } # removes the process from the list of jobs trap returntrap RETURN # is executed each time a shell function or a # waits until all background jobs have finished script executed with the . or source commands finishes executing

# 6. Tips and Tricks. # 8. Editing Files. # Edit text files directly from the command line. There are 3 main tools # set an alias # that can be used: 1) nano, the simplest and easiest to use, 2) vim, full cd; nano .bash_profile # featured but a steep learning curve, 3) emacs, shorter learning curve > alias clc='clear' # add an alias in .bash_profile # and extremely feature rich (generally not pre-installed).

# to quickly go to a specific directory nano # Launch nano with a blank file cd; nano .bashrc nano # Launch nano and open > shopt -s cdable_vars > export websites="/Users/mac/Documents/websites" # Commands onces inside nano source .bashrc CTRL-R # Open (read) a file cd websites CTRL-O # Save file CTRL-X # Close file # 7. Debugging Shell Programs. # Basic vim () commands vim # Launch vim with blank file bash -n scriptname # don't run commands; check for syntax errors only vim # Launch vim and open set -o noexec # alternative (set option in script) # Commands once inside vim bash -v scriptname # echo commands before running them set -o verbose # alternative (set option in script) :e # open to edit :w # Save file bash -x scriptname # echo commands after command-line processing :wq # Save file then quit set -o xtrace # alternative (set option in script) :q! # Do NOT save file and quit now (this one is important!) i # Insert text (vim starts in “command mode”, not edit mode) trap 'echo $varname' EXIT # useful when you want to print out the values ESC # Return to command mode (this is when you can save and exit) of variables at the point that your script exits # Basic emacs commands function errtrap { es=$? emacs # Launch vim with blank file echo "ERROR line $1: Command exited with status $es." emacs # Launch vim and open } $ Commands once inside emacs trap 'errtrap $LINENO' ERR # is run whenever a command in the surrounding script or function exists with non-zero status CTRL-X CTRL-F # Open a file to edit CTRL-X CTRL-S # Save file function dbgtrap { CTRL-X CTRL-C # Exit emacs echo "badvar is $badvar" } trap dbgtrap DEBUG # causes the trap code to be executed before every statement in a function or script

# ...section of code in the problem occurs...