TERMINAL BASICS
!!
- Repeat previous command
!!:/s/<search>/<replace>/g
- Repeat previous command with replaced string value
history
- Show bash history
!<int>
- Run a labelled command from history
id
- Show current user info
su <user>
- Switch user (enter root as user or leave blank for root privileges) (Default method in Red Hat, Fedora....)
sudo <command>
- Issue command with root privileges (Default method in Debian, Ubuntu, Mint....)
sudo !!
- Repeat last command with root privileges (Default method in Debian, Ubuntu, Mint....)
<command> !*
- Use argument from last command
<command> !:2
- Use second argument from last command
<command> !$
- Use ;ast argument from last command
<command>&
- Spin off command as new process to avoid terminal blocking
Ctrl + Z
- Suspend current process
bg
- Send suspended process to background process
fg
- Bring bacnground process to foreground
alias a="command"
- Set an alias (command shortcut)
~/.bashrc
- Add aliases here to use in all terminal sessions for user
clear
- Clears terminal window
man <command>
- Manual page for command
nohup <command> &
- Run command with hangup signals ignored (e.g. logouts / exits)
- Need ampersand to run in background
<command> | at <time>
at <time> -f <filename>
- Schedule a job (from prompt or file)
- Time in format HH:MM or now +<int> <minutes/hours>
info <command>
- Information about command
screen
- Launch screen (multi terminal manager, identified with ints)
- Ctrl-a C to create a new screen
- Crtl-a K to kill current screen
- Ctrl-a " lists screens
- Ctrl-a <int> to switch to specified screen
<command> --help
- Explain command syntax (work for most commands)
<command1> | <command2>
- Use between commands to feed output of command1 into command 2
<command> > <outfile>
- Use to redirect output (stdout)
<command> >> <outfile>
- Use to redirect output (and append rather than overwrite)
<command> < <infile>
- Use to redirect input (stdin)
<command> 2> <infile>
- Use to redirect errors (stderr)
<command> 2>&1
- Use to redirect errors to output (stderr -> stdout)
echo <string>
- Send string to standard out (useful for creating content to be redirected) e.g. add ' > <outfile>'
--
- Use to escape any further dashes in a command, e.g. 'find -name -- -f' will search for file with '-f' in name
*
- Represent wildcard in arguments
\n
- Represents new line
\t
- Represents a tab
SHORTCUTS
Ctrl + R
- Search Bash History
Up / Down Keys navigate history
Tab autocompletes (double tap for matches if more than one)
Left / Right / Home / End navigates line
Alt-b Alt-f goes to beginning or end of current word
Ctrl-u clears current line
Ctrl-l to clear screen
Ctrl-c to cancel current process
Ctrl-z to send current process to background (then enter fg command to get it back in foreground)
Shift-PgUP to scroll terminal up
Shift-PgDn to scroll terminal down
FILE SYSTEM TRAVERSAL / DIRECTORIES
pwd
- Display current working directory
cd <directory>
- Change current working directory
NOTE: . = current working directory, .. = parent directory, - = last working directory, ~ = home directory
rm <file>
- Delete file
rm -r <directory>
- Delete directory and contents (recursive)
rmdir <directory>
- Remove directory
mkdir <directory>
- Create directory
ls
- List content of current working directory
ls -l
- List content of current working directory (one per line with more information)
ls -A
- List all contents of current working directory (including hidden files)
NOTE: Directories are shown in blue when listing directory contents, red or green normally used for executable files, yellow for devices.
lsof
- List open files
basename <path>
- Returns last part of path (file if one present, if not then most nested directory)
//<server>/<folder> <localfolder> cifs auto,username-[username],password=[password],uid=0,gid=500 0 0
- Example cifs mount for in /etc/fstab
mount -a
- Mount everything in /etc/fstab
FILE OPERATIONS
cp [file] [location]
- Copy file to location
cp -r [directory] [location]
- Copy directory to location
mv [file|directory] [location\file]
- Move (or rename) file
ln [target]
- Create symlink to target in current working directory
ln -s [target]
- Create symlink to target directory in current working directory
truncate --size 0 [file]
- Truncate a file to 0 bytes (empty)
finger [file]
- Update file access time
touch [file]
- Create empty file
scp [[user@]host1:]<file1> [[user@]host2:]<file2>
- Secure file copy using ssh
- Use -r flag for copying directories
find [<path>] <expression>
- Find file matching expression
- Optional path points to root of search
expand -t 4 [filename] > tmp_file; mv tmp_file [filename]
- Replace tabs with 4 spaces, move file over temp version created in first command
unexpand -t 4 [filename] > tmp_file; mv tmp_file [filename]
- Opposite of previous commands
tar -cfv <archive> <files>
tar -xfv <archive> [<location>]
- Create archive OR Extract files from archive (without location will extact to current working directory)
- f is required to set the archive name (otherwise will use TAPE env variable?!)
- Add v to flag for full output
- Add w to flag to confirm each action
- Add z flah to enable compression / decompression
tar -t <archive>
- List file content so of archive
USERS & PERMISSIONS
chmod [maskOrModification] [file(s)]
- Alter file permissions
chmod -r [maskOrModification] [file(s)]
- Alter file permissions recursively
Modifications in form /(u+g+o+a+)([\+|\-])(r+w+e+)/ where:
- u is current user
- g is group
- o is others
- a is all
- + to add permissions
- - to remove permissions
- r is read
- w is write
- e is execute
Mask values:
- 4 is read
- 2 is write
- 1 is execute
- e.g. 655 is user (read / write), group (read / execute), others (read / execute)
chgrp <group> <file>
- Change group of a file
useradd -a -G <group-name> <username>
- Add user to group
- REMEMBER TO INCLUDE -a flag OTHERWISE user is MOVED not ADDED
TEXT MANIPULATION
cat <file(s)>
- Concatenate files and send to standard out
cat -n <file(s)> [> <outfile>]
- Add line numbers to concatenated string and optionally redirect to outfile
cat ><file>
- Redirect stdin to file
- Ctrl-C to finish (does not include last line in resultant file)
cat >><file>
- Same as above but appends rather than overwites
cut [-b <int|range>] [-c <int|range>] [-d <int|range> [-f <int|range>]] <file(s)>
- Cut a file into columns for standard out
- -b option to select a byte position / range
- -c option to select a character position / range
- -f option to select a field position / range (where field delimiter specified using -d)
sed [-n] '/<regex>/<command>' <inputfile> [> <outputfile>]
- Fine lines with text in inputfile and optionally put in outputfile
- -n makes command silent
- use !d or p (with -n) to show only matched lines
sed 's/<regex>/<replace>/' <inputfile> [> <outputfile>]
- Replaces matches text in infile and optionally put in outputfile
- Use N; before s to check multiple lines
- Use escaped brackets to capture and \<int> to use
e.g. 's/\(capture\)/\1/"
grep <string> <file(s)>
- Find a string in file(s)
- Use -i to make case insensitive
- Use -e for regex as string
- Use -B to specify number of lines to grab before match
- Use -A to specify number of lines to grab before match
zgrep <string> <file(s)>
- Same as grep but works with compressed files
awk <program> <file(s)>
- Find and replace / sorting / filtering using the awk language
- <program>
'<pattern> { <action> }
.....'
- omit pattern to match every line, omit action to print nothing, omit action and brackets to print whole matched line
- actions should be terminated with semicolons
- pattern can use /regEx/, &&, ||, !, ternary operator (a?b:c), range (a,b), before file read (BEGIN), after file read (END)
- Can match with special operators using ~ e.g. awk '$4 ~ /regex/ {action} //Do action if 4th field matched regex
- action can be a combination below as well as basic arithmetic:
- { print $X }
- if X is 0 then print whole line, else print Xth item on line
- { print <special>}
- NR prints line number
- NF print number of fields in line
- FILENAME prints current input filename
- e.g. $NR is last field
- Can use literal and escape chars e.g. "This\tis\ttext\twith\ttabs"
- Variable assignment: var=value;
- Operators ++, --, +, -, *, /
awk -f <script> <file(s)
- Same as above only reads program from file
sort <file(s)>
- Sort lines from file(s)
tr <set> <set>
- Replace values from standard in (e.g. add 'cat <file> | ' before command) print to standard out
- Characters in first set replaced by those in second e.g. [a] [b] replaces a's with b's
- Note [aa] [bc] would replace a with c
- A few character classes can be used instead of specifying whole set
tr -d <set>
- Same as above except removes characters without replace
tr -s <set>
- Same again except removes duplications of characters in set
wc <file(s)>
- Print byte, word, and line counts for a file (and filename)
- With multiple files, shows counts as well as total
- Use -c, -l, -w to return byte, line and work count only (and filename)
head [-<int>] <file(s)>
- Show top 10 lines of file (or specify number optionally)
tail [-<int>] <file(s)>
- Show last 10 lines of file (or specify number optionally)
- Add -F option to wait for new content (useful for log monitoring)
less <file(s)>
- Display file contents, line by line scroll with Enter
- F to wait at end of file for more content (useful for log monitoring)
- Q to quit
more <file(s)>
- Display file contents, line by line scroll with Enter
nl <file(s)
- Add line numbers
printf <format> <value>
- Use to format values
- Full list of modifiers: http://ss64.com/bash/printf.html
SYSTEM
uname -a
- Display kernel and OS version
date
- Show system date / time
- Use -u for UTC (local is default)
- Lots of formatting options (start with +)
- date +j% //days into the year
- date +d% //days into the month
- date +s% //UNIZ timestamp
time <command>
- Track time for command to complete
time cat
- Start stopwatch
shutdown -h now
- Shutdown (halt) now
shutdown -r now
reboot
- Shutdown (restart) now
df -h
- Disk usage statisics (all disks)
free -m
- Show RAM usage (in Mb)
du -sh
- Size of current directory / contents
top
- System resource usage statistics
- Hit h for shortcuts
ps
- Show running processes for current user
- Add -A to show for all users
- Add r to show running processes only
ps -A | grep <service>
- Search for a service's runnning process
kill <processId>
- Kill a process (can chain multiple space delimited processIds)
killall <name>
- Kill a process by name
w [<username>]
- Show logged in users and what they are currently doing
- Optionally specifiy a user
strace -t <command>
- Trace execution path of command with timestamps
strace -t -p <pid> [-o <outfile>]
- Trace a process with timestamps and optionally write to outfile
fuser [-k] <file>
- Find process which is using a file
- Add -k flag to kill process
NETWORKING
/etc/init.d/network [restart|start|stop]
- Restart networking
/sbin/ifconfig -a
- Display interfaces
ifconfig
- Display and set networking / interface settings
/etc/network/interfaces
- Network interface config file
ping <host>
- Standard icmp ping
traceroute <host>
- Routing info / connection debug
mtr <host>
- Advanced traceroute / ping
netstat
- Networking settings
nslookup [host|address]
- DNS lookup
nmap [host]
- Port scanning
mount -t cifs -o username="[username]",password"[Password]" //[IP]/[folder] [folder]
- Mount network drive
route -n
- Show routing
route del [-host|-net] [ip] netmask [netmask]
- Delete route
route add [-host|-net] [ip] netmask [netmask] gw [ip] dev [interface]
- Add route
route add [-host|-net] gw [ip] dev [interface]
- Add default route
hostname [new]
- Show or with argument set hostname
wget [address]
- Fetch file from web
APTITUDE (Package Management in Debian, Ubuntu, Mint...)
apt-cache search <package>
- Search apt cache for program / package
- Use ^package$ for exact match
- Use "package" for description search
apt-cache show <package>
- Show basic package info
apt-cache showpkg <package>
- Show detailed packaged info (including dependancies)
apt-cache depends <package>
- Show dependancies for package
apt-get install <package>
- Install a program / package
apt-get --purge remove <package>
- Completely remove a program / package
apt-get autoclean
- Erase old downloaded archive files
apt-get --purge autoremove
- Remove automatically all unused packages
apt-get update
- Update package index
apt-get upgrade
- Update installed packages
APACHE (Web Server)
/etc/init.d/httpd [restart|start|stop]
- Control web server
/etc/httpd/conf.d/httpd.conf
- Main settings file
APACHE2 (Web Server)
/etc/init.d/apache2 [restart|start|stop]
- Control web server
/etc/apache2/apache2.conf
- Main settings file
a2enmod [module_name]
- Enable module
a2dismod [module_name]
- Disable module
CRON (Scheduling)
crontab -e
- Edit user cronjobs
crontab -1
- Display user cronjobs
/var/spool/cron/
- Cronjob files location
/var/log/cron
- Cron log files location (legacy)
/etc/init.d/cron [restart|start|stop]
/etc/init.d/crond [restart|start|stop]
- Control cron service
GZIP (Compression)
gzip <file>
- Compress file
gzip -d <file>
- Decompress file
MINICOM (Serial Connection)
minicom
- Launch
minicom -s
- Setup
minicom -c [file]
- Launch with output capture file
RSYSLOG
su -c '/sbin/service rsyslog restart'
- Restart
/etc/rsyslog.conf
- Config file
rsyslogd -f/etc/rsyslog.conf -N1
- Run debug mode
VIM (Editor)
vi <filename>
- Edit / create file
VSFTP (FTP Server)
/etc/vsftpd.conf
- Settings file
/etc/init.d/vsftpd [restart|start|stop]
- Control service
YUM (Package Management for Red Hat, Fedora...)
/etc/yum.conf
- Config file
yum clean all
- Clean yum cache
yum list [package]
- Search for package
yum install [package]
- Install package
yum downgrade [package]
- Rollback package to previous version
yum check-update
- Check for updates for installed packages
yum update
- Update installed packages
yum update [package]
- Update package
LOCATIONS (some important ones)
/etc/rc.d/rc.local
- Startup script location
/etc/fstab
- Config for mounted drives / swap space
/var/log/
- Main logs directory
/var/null
- Unix blackhole (EOF on read, all write lost)
/usr/local/bin
- Drop executable scripts here to make available as system wide commands
/etc/sudoers
- Sudoer settings
/etc/environment
- Global environment variables