This is meant to be a quick reference guide to command-line usage for those of us
who have the basics down, but aren't yet true ninjas. Please add your own tips
or quick examples! We spend a surprising amount of our lives inside a terminal,
so learn to love it and use it well. Note: this page was written for bash
,
but much of this stuff should translate to csh
or your shell of choice.
General notes about navigation commands: First, “Ctrl” commands are the same as in the text editor emacs, so you may find that other emacs line navigation commands work as well. Second, if you are on a Unix machine, note that the line navigation commands work almost anywhere you can edit text - you will learn that accidentally if you start using these commands compulsively. Third, if you use “Ctrl” commands often, you may consider setting the “Caps Lock” key as an additional “Control” key - this is just a computer setting for Unix (e.g. System Preferences > Keyboard > Modifier Keys) but requires slightly more work on Windows (e.g. the AutoHotkey program).
cntrl-a
: go to beginning of linecntrl-e
: go to end of linecntrl-k
: delete everything to rightcntrl-u
: delete everything to leftcntrl-w
: delete word to leftoption
or cntrl
)-(left
or right
): move left/right. cntrl
for linux, option
for mac.\
to literally interpret any command characterscd
: go homecd -
: go back to previous working directory~
: stand-in for home directoryls ~/Documents
!!
: repeat previous command!xxxx
: repeat most recent command that starts with xxxxcntrl-r xxxx
: search recursively through history for match to xxxxcntrl-r
again to cycle through matchesenter
to execute^this^that
: rerun most recent command, but replace this with thathistory
: shows history of recent commandshistory | grep xxxx
: search for command xxxx in history!xxxx
: repeat item number xxxx in historycntrl-x-e
: invoke your editor to compose a hairy commandcp file.{txt,txt.backup}
: same as cp file.txt file.txt.backup
cp file_{,copied}one.txt
: same as cp file_one.txt file_copied_one.txt
rm file_{a,b,d,g}.txt
: same as rm file_a.txt file_b.txt file_d.txt file_g.txt
clear
: clear the terminal screencntrl-z
: shunt something to the backgroundfg
: to get it backman xxxx
: display manual for xxxxwhich
or whereis
) xxxx
: display path for xxxxwc xxxx
: character, word, and line count on file xxxxwc -l
: return only line countcat xxxx
: display contents of file xxxxhead -n 10 xxxx
: display first 10 lines of file xxxxtail -n 10 xxxx
: display last 10 lines of file xxxxgrep xxxx yyyy
: search for xxxx in file yyyyfind path xxxx
: search for files with names matching xxxxkill xxxx
: kill (end) process with process id xxxxtop
: display running processes and system infoq
: quitk xxxx
: in linux, kills process with id xxxxps -e
: show all running processesps -e | grep xxxx
: search for xxxx amongst running processesdate
: print date & timedate +%H:%M:%S
crontab
: fully-functional command schedulerat
: a simple one-off schedulercmd | at time
: schedule cmd to run at timels ~/* > ~/home_dir.list | at 3:05pm
screen
: like VNC but only for the terminal, lets you start a session and then disconnect and reconnect at willscreen
to connectscreen -d
to disconnectscreen -r
to reconnectscreen -list
to show current sessionsscreen -r xxx
to reconnect to session with PID xxxssh
sessionsBest way to install and manage command-line tools. Native for all linux builds; have a couple good choices for macs.
cmd &
: run cmd in subshellcmd1 ; cmd2
: run cmd1 then run cmd2cmd1 && cmd2
: run cmd2 after cmd1 only if cmd1 is successfulcmd1 || cmd2
: run cmd2 after cmd1 only if cmd1 is not successfulcmd > file
: sends output of cmd to filecmd >> file
: appends output of cmd to filecmd1 | cmd2
: connects stdout of cmd1 to stdin of cmd2cmd 2> file
: sends error of cmd to filecmd 2>> file
: appends error of cmd to filels not.a.file* 2> output; cat output
cmd > output 2> errors
: save output and errors of cmd separately, in files output and errorsls * not.a.file* > success.out 2> failure.err
cmd < file
: sends file to cmdsort
: sorts stuff alphanumericallyls | sort
xargs cmd
: a piping glue - runs cmd with standard input as argumentsecho one two three > test.txt; xargs echo < test.txt
echo -e 'one\ntwo\nthree' > test.txt; xargs echo < test.txt
ls | sort | xargs echo
awk
: programming language to edit pipes on the flyawk '{print $1}
: print the first item of each line, items split by spaces/tabsawk -F, '{print $2}
: print the second item of each line, items split by ,
ps -e | grep python | awk '{print $1}' | xargs kill
ls | awk '{sum+=1; print sum “: ” $1}
'NA
with the number 0
in a filecat file.txt | awk '{gsub(“NA”, “0”); print $0}' > clean.file.txt
Variables that have already been declared are prefaced by a $
, but you don't need
one when first declaring a variable. Any variables declared normally (x=4
) are considered strings,
to declare a number use the let
keyword: let x=4
. You can also declare a variable to be a command by
wrapping it in back-ticks or parentheses. I.E. LIST=(ls); $LIST
.
There are some system-wide variables that should always be available, like $SHELL
, $PATH
, and $HOME
.
Note that though convention says system-wide variables should be all caps, they don't need to be.
There are several ways to write loops, the most useful of which are below.
Note that in bash an $
always indicates a variable, and that all variables are,
by default, treated as strings. The actions to be repeated must be wrapped in
do/done
statements, and the semicolon marks an end-of-statement (equivalent to a line return).
A few examples:
for i in {1..20} do echo $i done
for i in {a,b,d,g}; do echo $i; done
for i in a 2 b 6; do echo $i; done
for file in *filePattern*; do echo file; done
The shell can do arithmetic and logic tests, but I think if you're doing
anything very complex you should move into Python
or Perl
. Logic comparisons
should be put in square brackets (spacing is important), if
statements must
be closed with a fi
, and the operators you have at your access are:
==
: string equality!=
: string inequality-eq
: number equality-ne
: number inequality-gt
: greater than-lt
: less than-ge
: greater than or equal-le
: less than or equal&&
: and||
: orUse aliases to make hard-to-remember commands less terrible.
Example: http://xkcd.com/1168/:
alias maketar='tar -czvf
'alias untar='tar -xzvf
'
You can declare functions and use them at any time. The most common way
to interact with functions is through required arguments, as shown below.
Adding in flags (like -v
) for optional arguments takes some more work
(look up getopts
).
$#
: number of parameters passed$@
: array of all parameters$N
: the Nth parameter passed to the function, with $0 being the function nameSome examples:
function speak () { echo here are all $# arguments: $@ echo here is argument 1: $1 echo here is argument 3: $3 }
function killme () { ps -e | grep $1 | awk '{print $1;}' | xargs kill echo $1 is dead }
function cls () { cd $1 ls }
There are a set of system files in your home directory that are executed every time a terminal is opened - use those to define aliases, functions, or variables you want always available.