Linux Commands
From TheBeard Science Project Wiki
Updated 6/28/2018
exit #TO PREVENT EXECUTION OF THIS FILE
su <user> - switch user
-c 'command' - execute a command as user
-l - setup environment like user instead of keeping your own
gksudo - use for graphical applications
-u <user> - do command as user
-k - preserve environment variables
-D <text> - name of program to display
-m <text> - replace whole message with text
-p - print password to stdout
man <command> - searches manual
-k <keyword> - search man for keyword
; - separate multiple commands
# comment
: - produces no output. Can be used as a "non-value" like:
while :;do something forever;done
: '<comments with new-line characters>' - allows multiple-line comments
shift + page up or down - scroll
-- - signifies end of command and beginning of arguments (or last argument)
ctrl + c - kill process in foreground
ctrl + u - kill a line
ctrl + l - clear
ctrl + alt + f1 - bypass gui
ctrl + alt + f7 - return to gui
ctrl + d - logout
esc + . - insert parameters from last command
ctrl + alt + e - expand all string expansions and show it before executing it
ctrl + r - search command history
hold shift during boot to get grub menu
put commands in .bashrc in home dir to run command at login
gconf-editor - "registry" for Gnome
use to remove desktop folders from fedora. go to /apps/nautilus/desktop.
dconf-editor - similar to gconf-editor
alacarte - graphical gnome menu editor
cheese - webcam program
webcamoid - better webcam program
find <location> -name <file> - look for file
-iname - case insensitive (use instead of -name)
-type <type> - d=directory, f=file, l=link, b=block, c=character
-maxdepth <#> - number of directories down to look
-regex <pattern> - look for pattern (matches whole file path, not just name)
-iregex - case insensitive regex
find /u1/database/prod/arch -type f -mtime +3 -exec rm {} \; - find files that are older than 3 days and remove them
locate - search
-c - count instead of output
-i - ignore case (not case sensitive)
-r - regex
eog - graphical image/picture viewer
VBoxManage - virtual box manager
modifyhd --compact <file.vdi> - compact a dynamically expanding disk
list runningvms
list vms
startvm --type headless "VM Name"
pwd - print working directory
ls - alternative to dir
-a - show hidden
-l - more info
-R - recursive
-Q - enclose entries in double quotes
-d - list only directories
-h - human readable file size
-t - sort by most recent modification date
-r - reverse order (reverse alphabetical, or reverse mod time if used with -t)
-1 - list in one column
-i - list inodes
-f1 - can list directory with too many files
pushd - remember current directory (need to do "pushd ." the first time you use it per session)
popd - navigate to remembered directory
file <file> - list file info
-i - shows filetype and charset
stat <format> <file> - list file info (format if optional)
%a - permissions in octal
%s - size
getfacl <file/dir> - get ACL and umask info
setfacl -d <file/dir> - set ACL for default umask
-m <perm> - add ACL (ie. u::rwx [can do o::- to remove])
hachoir-metadata - show metadata of file
mv <file> <destination> - move/rename
<file> <newfile> - can be used to change name of file
-n - no clobber (do no overwrite file if it already exists)
-u - update: only move if source is newer than destination
-f - force
cp - copy
-r - recursive
-f - force
-i - interactive
-l - link
-n - no clobber (do no overwrite file if it already exists)
-u - update: only copy if source is newer than destination
-p - preserve permissions
-s - symbolic link
rm - remove/delete
-r - recursive
-f - force
-i - interactive
rmdir - delete directory (must be empty)
mkdir - make directory
-p - create parents (of dir1 does not exist, running mkdir -p dir1/dir2 will create it)
ln -s <file> [<link name>] <dir> - make a symbolic link of a file in this dir
tar <options> <archive.ext> <backupstuff> - archiving tool (combine)
-p - preserve permissions
-z - use gzip compression
-j - use bzip2 (add .bzip2 ext)
-c - create
-x - extract
-f - file to create/extract (must be last option as in -pjcf)
echo - print something
-e - interpret escape characters (ie. \\, \n, \r, \b, \t, \xHH; see more under "escape characters" in this file)
-n - no trailing noe-line character
echo 'message' | smbclient -M windows_box - Send popup to windows machine (off by default in XP sp2)
echo "error" >&2 - send "error" with rest of error output
echo $(( 100+(`od -An -N2 -i /dev/random` )%(1000-100+1) )) - random # between 100-1000
less - view text file
-i - ignore case in searches
PageUp or Ctrl+b - page up
PageDown or Ctrl+f - page down
g - top of page
G - bottom of page
/<pattern> - search for pattern
more - old line-by-line file reader
cat - print contents of text file
-n - print with line numbers
-b - number non-blank lines
-v - show non-printable characters
- - take from standard input (ie. echo "hello" | cat -)
tac - print lines in reverse order (similar to cat)
strings <file> - print any ascii characters in a binary file
<command> > <filename> - writes output of command to file
<command> >> <filename> - appends output of command to file
<command> < <filename> - sends contents of file to command
<command1> | <command2> - feed output of com1 into com2
|tee <file> - puts output into file and echos
1> <place> - redirect standard output
2> <place> - redirect standard error
2>&1 - redirect error to same place as output after output has been redirected
&> <place> - redirect both stdout and stderr
command < infile > outfile - combinations of redirects
exec 3<>/file - set file as place to redirect 3
echo hi >&3 - redirect
3<&-;3>&- - disables
set -o xtrace;exec &>/file - set commands to echo before executing, and redirect all output to file. Good way to log everything you do.
sort -d - sort by alphanumeric
-u - sort and remove duplicates/repeats/doubles
uniq - show or omit repeat lines (lines must be sorted first)
-c - count number of occurrences
-d - only print duplicate lines
-u - only print unique lines
-cd - count duplicate lines
-cu - count unique lines
diff <file1> <file2> - difference between files
-y - side-by-side output
--suppress-common-lines - does what it says
basename <string> - strip/trim/cut filename in full pathname (ie. /dir/file --> file)
dirname <string> - strip/trim/cut pathname(ie. /dir/file --> /dir)
head - print the head of the input
-N - where N is the number of lines
-cN - where N is the number of characters
-c-N - where N is the number of characters to cut off at the end
tail - print the tail of the input
-N - where N is the number of lines
-cN - where N is the number of characters
-c+N - where N is the number of characters to cut off at the beginning
-f <filename> - continuously watch the bottom of a file. Good for monitoring log files or nohup files.
cut - cut text. Pipe or specify filename (|cut -cN where N represents bytes, or cut -cN file.txt).
by default, cut will output bytes specified.
--complement - will output all except specified bytes.
-cN,M,O - list of bytes
-cN-M - range of bytes
-dC -fN - delimiter character C, pull field N (cut -d: -f1 /etc/passwd will give you usernames)
fold - wrap each input line to fit in specified width
-w N - wrap with a screen width of N columns
-s - wrap on spaces
aspell - spell checker. Can be used like "cat file.txt|aspell list"
grep specific line: <output> | head -2 | tail -1 | grep <string>
-r - recursive
-B<#> -A<#> - display # number of lines before and after pattern
-E - extended regex
-e - enter multiple expressions like: -e "EXP1" -e "EXP2"
-G - basic regex
-P - perl regex
-v - show non-matching lines
-i - ingore case
-c - count lines instead of output
-n - include line numbers in output
-l - list files that contain matching lines
-L - list files that do not contain matching lines
-o - print only matching string
-q - no output
-s - no error messages
egrep - uses regex. same as grep -E
fgrep - does not use regex
pgrep - grep process tree
grep -i "$1" <<+ - uses everything between the +'s as input.
thing1
thing2
+
sed 's/hello/goodbye/g' - replace
's/hello/goodbye/g;s/hi/bye/g' - multiple statements (delimited by a ';')
's/hello/goodbye/n' - replace the nth occurrence
'/string/ s/hello/goodbye/g' - search first for line that matches 'string' then replace within that line
'/string1/,/string2/p' - search all lines between tags string1 and string2, then print them
'/^\s*\?string1/' - match string1 with zero or more spaces before it
'/^\s*$/d' - delete empty lines
'/./,$\!d' - delete empty lines at beginning of stream (ie. at top of file)
NOTE: Non-standard versions of sed may require [[:space:]] instead of \s for whitespace.
sed -i 's/apple/banana/g' file.txt - replace string in a file "in place" (changes the file). Use '-i.bak" to save a backup of the original with a .bak extension.
cat file | sed -n '/string1/,$p' | sed '/string2/,$d' - print all lines between string1 and string2
(including string1, excluding string2)
awk -F, '{print $3}' file.csv - print 3rd column in comma-delimited file
od -t x1 -w 32 <file-or-output> - display ascii in hex(1byte) width of 32bytes (16 default)
hd, hexdump, xd, xxd - other common hex dump programs
ghex - good graphical hex editor
nl - count line numbers (ie. cat file|nl)
tr - translate (pipe output to tr)
tr '123' 'abc' - turn 1>a 2>b 3>c in a file (pipe from cat)
tr '[A-Z]' '[a-z]' - uppercase to lowercase
tr -d '[0-9]' - delete
tr -cd '[0-9]' - delete all except these characters
tr -d '[:print:]\r\n\t' - delete non-printable characters
wc - count length of something
-c - bytes
-m - characters
-l - lines
-L - length of longest line
-w - words
exit 0 - exit with normal status
exit 1 - exit with error status
true - produce 0
false - produce 1
dmesg - kernel dump
last - login log
who - who is currently logged on
w - who is currently logged on and more
finger <user name> - user info
will show the contents of .plan, .project, and .pgpkey files in home folder
id <user> - user details
users - list of users currently logged on
date - the date
+%s - epoch time
+%Y%m%d%H%M%S - Year Month Day Hour Minute Second
+%Y-%m-%d_%H:%M:%S - character delimited
+"$Y %m" - quoted to allow space
+%T - same as %H%M%S
+%r - 12 hour time
+%u - day of week
d=`date +"%F %s"`;dt=`echo $d|awk '{print $1}'`;ep=`echo $d|awk '{print $2}'` - get date and epoch in one date command
cal - display calendar
-3 - show 3 months (previous, current, next)
-y - show whole year
dpkg-reconfigure tzdata - set timezone
info - info on things
help - find info for bash built-in commands
free -m - memory info in MB
lshw - list hardware
lspci -v - list extensive hardware info
lsusb - list USB devices
ipcs -a - list IPC ramdisk usage. Ramdisk is mounted at /run. (IPC: Inter-Process Communication)
lscpu - list CPU info
nm-tool - network device report
df -h - disk space (human readable)
du - file sizes
-c - print total at the end (pipe to tail -1 to only see total)
-h - human readable
mount -t <type> -o <option,option...> //server/share /mnt/mountpoint
-t - type
cifs - better choice than smbfs
nfs
-o - options
ro - read-only
rw - read/write
dev - interpret special devices on filesystem
nodev - do not interpret devices
noperm - sometimes fixes permissions problems
exec - allow execute
noexec - do not allow execute
loop - allows an image file to be mounted
group - allow normal users to mount filesystem if they are in the same group as the device
owner - allow normal user to mount if they are the owner of the device
user - allows the ordinary mounting user to mount/unmount the fs
users - allows all ordinary users to mount/unmount the fs
remount - attempt to remount
suid - set uid
nosuid - do not set uid
uid=<name or #> - set uid
guid=<name or #> - set guid
guest - allow guest access
username=<name> = username for filesystem
password=<pass> - password
credentials=<file> - give credentials file instead of username and password
format: username=<name>
password=<pass>
umount /mnt/mountpoint- unmount the share
showmount <host> - shows hosts with shares or shows shares on <host>
-a - show all
losetup <target> <source> - setup a loop device, can map a partition from a disk image
-o <offset> - offset of partition from file (fdisk: sector size * start)
-d <devfile> - detach loop device (-D to detach all)
-l - list all attached loop devices
-r - attach as read-only device
-f - find next unused loop device
<target> - usually /dev/loop0 (or 1, 2, etc.)
<source> - the source file (ie. disk.img)
Note: after setting up the loop device, you can install a fs on it and mount it
shred -u <file/directory> - securely delete files
srm - securely delete files (part of package "secure-delete")
sfill - securely overwrite empty space. use tune2fs to free up reserved space. (part of package "secure-delete")
sswap - securely overwrite swap partition (part of package "secure-delete")
sdmem - securely overwrite free ram (part of package "secure-delete")
chkrootkit - rootkit scanner
rkhunter - rootkit scanner
clamav - anti-virus
lynis - vulnerability scanner
debsecan - vulnerability scanner
tiger - vulnerability scanner
yasat - audit tool
bleachbit - disk/cache cleaning, drive wiping, etc.
acct - process and login accounting (audit tool)
accton <filename> - start accounting and log to filename
accton off - turn accounting off
dump-acct <filename> - read an accounting file in human readable format
dvdbackup - great dvd ripping on the command line
steghide - steganography tool. hides/embeds data into other data.
ffmpeg -i <input.file> <output.file> - extract audio from video. Extension of output file determines output format.
growisofs -dvd-compat -Z /dev/dvd=/path/to/image.iso - burn image to DVD
convert file1.png file2.txt outfile.pdf - convert several different file formats to pdf pages
fdisk <device> - manipulate partition table (ie. fdisk /dev/sdb; can also provide filename)
-l - list disks (pipe to grep "^Disk" for sleekness)
echo -e "n\np\n1\n\n\n\nw\n" | fdisk <devname> - automatically create partition
sync - write changes to disk (do 'cat /proc/meminfo|grep Dirty' to watch progress)
dd if=inputfile of=outputfile bs=4M count=4 seek=2 conv=notrunc,noerror
bs - block size
count - copy only N blocks
seek - skip N blocks at start of output (where you are writing to)
skip - skip N blocks at start of input (where you are reading from)
notrunc - do not truncate
noerror - no halt on error
kill -USR1 $(pgrep ^dd) - send USR1 signal to dd to get output of its progress (run this from another terminal or with dd running in the background)
ddrescue <source> <destination> [<logfile>] - dd for damaged drives (from package "gddrescue")
-r <n-retries> - number or retries per block
-v - verbose
fsck <device> - check UNMOUNTED filesystem
hdparm <option> <device> - hard disk information
-t - benchmark transfer rate
-C - Check the state of a device
-g - show disk geometry
-y - Force the drive into standby (spin down)
-f - Sync and flush buffer cache
-F - Flush the on-drive write cache
-S[0-240] - Set disk timeout (spin down). Number is in seconds times 5. (eg. -S120 is 10 minutes)
iotop -botqqq - I/O monitoring of disk read/write. If you want to write the output to a log file, place the file in a ram disk (tmpfs) to prevent disk usage.
-b - batch (continuously log)
-o - only show active I/O
-t - timestamp
-qqq - quiet. No header or summary info.
iostat -m -p <dev1>,<dev2>,... - show I/O statistics
tune2fs <option> <device> - manipulate filesystem
-m <#> - change % of reserves blocks on partition (set to 0 to maximize storage space)
-l - show extensive filesystem info
-j - add journal
-L <label>
wipefs <device> - wipe filesystem signature. Alone, it shows a table of offsets of signatures on device.
-o <0x#> - offset of signature to delete
-a - erase all signatures
-n - dry run
addpart <device> <#> <start> <length> - add a partition (ie. addpart /dev/sdb 1 0 2048)
start - start point
length - length in 512 byte blocks
!still don't know how to write table to disk!
delpart <device> <#> - delete partition (ie. delpart /dev/sdb 1)
mkfs <device> - make a file system
-m <#> - % of reserves blocks on partition (set to 0 to maximize storage space)
-t <type> - ext2, ext3, ext4, msdos, vfat
-L <label>
-j - create journal
-c - check for bad blocks before write
-q - quiet
blkid - list file systems
lsblk - list file systems in a tree format
mkswap <file> <bytes> - make the file into a swap file. follow it with 'sync' command to finalize.
mkswap <device file> - make a partition into swap space. Partition but be "Linux swap / Solaris" type.
swapon <file> - initialize the swap file. To make permanent, add swap to fstab (/dev/sda2 swap swap defaults 0 0).
badblocks -s /dev/sda - test main drive for bad blocks
ntfsprogs - a collection of ntfs tools for working with and fixing ntfs.
ntfsfix <device> - one of the tools in ntfsprogs. very useful.
dmidecode - view ALL hardware info
uname -a - kernel/system info
hostname - show hostname of system
hostname <name> - temporarily change hostname to <name>
-f - show fqdn of system
arch - system architecture
route - manage routing table
route add -net 0.0.0.0 netmask 0.0.0.0 gw <gtwy-addr> - set default gateway
route del <route> - deletes route
routel - route with nicer output (more verbose)
routef - flush routing table
ldd <file> - show library dependencies of a program file
vbetest - test screen resolution
add 512 to number in bracket and put as vga=XXX to set res at boot
chntpw - change password for windows xp
calibre-bin - e-book converter
mknod <name> <type> <major> <minor> - make new device file
example: mknod /dev/new b 1 0
-m XXX - permissions
lsmod - list modules
modinfo <module> - information about module
rmmod <module> - remove module
insmod <module> - insert module
modprobe <module> - manipulate modules
-r - remove
-f - force
synclient - manage touchpad mouse settings
synclient MaxTapTime=0 - disable touchpad clicks. default: 180
ifconfig - network info
ifconfig <interface> <address> netmask <mask> - set static ip
ifconfig <interface> hw ether <mac addr> - spoof mac address
ifconfig <interface> <com> - configure interface
up
down
promisc - enable promiscuous mode
-promisc - disable promiscuous mode
iwconfig <interface> <options> - wireless interface configuration
mode monitor - enable monitor mode
mode managed - disable monitor mode
mode ad-hoc - enable ad-hoc
mode master - act as access point
mode repeater - act as repeater
mode secondary - act as master/repeater
nmcli - Redhat (CentOS)
nmcli d - brief stats
nmtui - Network Manager terminal UI.
hciconfig - bluetooth interface configuration
nmap - port scanner
nmap -A <host> - scan all the things
nmap -sn <network> - get only MAC addresses and IPs for all hosts
netstat - network info
-s - statistics
-l - listening ports and services
-r - routing table
-i - interfaces
-p - show pids
-t - tcp
-u - udp
-a - all
lsof -i - list processes that are listening on the network
nslookup <hostname/addr> - dns lookup
dig <hostname> - dns lookup
dig -x <addr> - reverse name lookup
tracepath - equivalent to traceroute or tracert
dhclient -4 <interface> - set interface to dhcp (ip4)
whois <hostname/addr> - domain info
wget <options> <url> - download into working dir
-r - recursive
-l <#> - depth for recursion
-H - span hosts for recursion
-np - no parent directories
-nd - no directories
-k - convert links for local viewing
-A <list> - accept
-R <list> - reject
-b - run in background
-i <file> - download from list of URLs
-m - mirror. use for downloading whole site
-p - page requirements. use for downloading whole page
-o <file> - log file
--user-agent=<text> - mask wget as a browser
to mask as firefox: "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.3) Gecko/2008092416 Firefox/3.0.3"
curl <url> - make http requests
--connect-timeout <seconds>
-m <seconds> - max time for whole operation
-i - include http header in output
-I - retrieve header only
-x <host:port> - proxy
-s - silent
--socks4a <host:port> - socks4a proxy
-o <filename> - output file
-O - output to file with same name as remote file
tsocks <command> - ports command through proxy
tor uses socks4a
use with tor - under /etc/tsocks.conf change lines to:
server = 127.0.0.1
server_type = 4
server_port = 9050
html2text - converts/parses html into text
dos2unix - convert DOS line delimiters (\r\n) to UNIX line delimiters (\n)
unix2dos - convert UNIX line delimiters (\n) to DOS line delimiters (\r\n)
unix2mac - convert UNIX line delimiters (\n) to Mac line delimiters (\r)
mac2unix - convert Mac line delimiters (\r) to UNIX line delimiters (\n)
minicom - use to configure routers via com/serial port.
nc <host> <port> - create tcp/udp connection (also called netcat)
ports can be specified as range x-y
-l - listen
-k - keep listening (must be used with -l)
-4 - ipv4
-6 - ipv6
-u - use udp
-w <#> - timeout in seconds
-n - no dns or service lookups
-x <address> <port> - proxy
-X - proxy protocol
4 - socks4
5 - socks5
connect - http
-s - source address
-p - source port
-z - scan host if port is open (only works if a service is listening on the host)
write <username> - write a message to someone logged on
mesg y - allow messages
mesg n - deny messages
vim - text editor
i - insert mode
r - replace mode
o - add new line under cursor and enter insert mode
esc - command mode
k j h l - up, down, left, right
yy - yank current line (nyy - yank n lines including current line)
p - put line (after current line)
u - undo
U - undo line
ctl-r - redo
x - delete
dd - delete line (and save to clipboard; similar to cut)
J - delete newline at end of current line
~ (shift+grave) - toggle upper/lower case
G - go to last line
1G - go to first line
<n><x> - do x n number of times (ie. 100dd, 20x, 50yy)
:q - quit
:q! - force quit
:w - save
:wq! - save and quit (force)
:set number - line numbers (set nu)
:set nonumber - no line numbers (set nonu)
:set mouse=a - enable mouse
:syntax on/off - enable/disable syntax highlighting
:set ignorecase - case insensitive searches (set ic)
:set noignorecase - case sensitive searches (set noic)
:set smartcase - enable smartcase searches
:set nosmartcase - enable smartcase searches
:s/string1/string2/g - search and replace a single instance on a single line
:%s/string1/string2/gc - search and replace (%s=search all lines, g=replace, c=ask for confirmation)
bvi - binary vi editor (hex editor)
nuitka --portable script.py - python compiler. Compiles a Linux executable from script.py
apt-get update - update package lists
apt-get upgrade - install latest package versions
apt-get install <package> - install a package
apt-get install -f - fix missing packages
apt-get source <package> - download source code
apt-get download <package> - download the package binaries
apt-get remove <package> - removes a package
apt-get purge <package> - removes a package and its all configs
apt-get clean - clears the local cache
apt-get autoclean - intelligently clear the cache of "useless" stuff only
apt-get autoremove - uninstall packages that are no longer necessary
-y, --yes - assume yes
--force-yes - more dangerous
--reinstall - reinstall a package
apt-cache search <regex> - search package names and descriptions
apt-cache show <package> - show info about package (including dependencies)
apt-cache depends <package> - show dependencies (and alternatives)
apt-cache rdepends <package> - reverse dependencies (packages that depend on this one)
-f, --full - show full package info in search results
apt-mark hold <package> - hold a package; prevent automatic updating
apt-mark unhold <package> - remove a package hold
apt-mark auto <package> - mark a package as automatically installed
apt-mark manual <package> - mark a package as manually installed
apt-mark showhold - show a list of holds
apt-mark showauto - show a list of automatically installed packages
apt-mark showmanual - show a list of manually installed packages
apt-config dump - show all apt configurations
dpkg - debian package manager
-l - view all packages installed
-i <file> - install deb file
-I <file> - info about file, including dependencies.
-r <package> - remove package
-P <package> - purge package
-C - audit. search for partially installed packages.
--configure <package> - configure a package
--force-all - force the operation
dpkg-query -W - view all packages installed (full package name)
do-release-upgrade - upgrade distro (debian)
export DEBIAN_FRONTEND=noninteractive - disable confirmations during apt-get install
rpm - red hat package manager
-i - install
-U - update
-e - erase/uninstall
-qa - list packages in Red Hat
-ql <package> - list files owned by package
-qi <package> - more info on package
-qf <file> - which package a file belongs to
--initdb - initialize database
yum - package installer for Red Hat
yum check-update - list packages with available updates
yum clean all - cleans packages
yum search <word> - searches repositories
yumdownloader - downloads, not installs, rpm packages
--destdir <dir>
--source
--resolve - download dependencies as well
yum-utils - package contains several yum tools, including yumdownloader
./configure && make && make install - install form source, first cd into directory
createrepo <dir> - make a software repository
ps - active processes
-e - all processes
-f - full info
-l - even more info
aux - a good long-list format
pstree -r - process tree
pgrep -l <string> - grep process tree
pmap -x <pid> - show how a process is using memory
top - system monitor
z - toggle colors
Z - change color mapping
B - toggle bold
b - toggle bold/reverse
<,> - change sort field
x - toggle highlight sort field
y - toggle highlight running processes
c - toggle full command names
k - kill process
r - renice. change NI value to alter priority
d or s - set update interval
W - write config file
h - help
q - quit
l,t,m - toggle summaries at top
1 - toggle CPU display
I - irix/solaris mode
i - idle processes
f - change fields
o - change display filter (FIELD=STRING)
F or O - sort field
R - reverse sort
H - toggle threads
S - toggle cumulative time
u - show specific user only
n or # - set max tasks displayed
atop - another tool for monitoring system activity
mpstat - CPU usage (performance, system status)
iostat - display disk/drive stats
-m - display in Megabytes
-p <hd1,hd2,...> - display only these devices
ioping <dev> - a ping-like tool for block devices
jobs -l - active jobs
jobs -p - jobs by process #
bg <job#> - starts a paused job and runs in background
fg <job#> - brings job to foreground
<command> & - run in background
ctrl+z - pauses job
kill <pid> - kill process ID
%<#> - kill job number
-N - where N is a number that represents a signal (ie. -9 is SIGKILL)
-s <signal> - send specified signal to process (ie. TERM)
-<signal> - short form of -s <signal>
-USR1 - user-defined signal 1. dd responds by printing its progress!
killall <process name> - kill process by name (extremely dangerous! Don't run without a parameter!)
-I - ignore case
-i - interactive
-r - regex
-u <user> - kill all processes for user. command name is optional
xkill - xfce4 tool to kill and unresponsive program. Create a launcher in the panel and put 'xkill' as the command.
for x in 'jobs -p';do kill -9 $x;done - kill all jobs
WHITESPACE PROBLEM - $IFS is used to determine field separator. It usually includes all whitespace, so to process line by line, do this:
s=$IFS
IFS=`echo -en "\n\b"`
for x in $whatever;do something;done
IFS=$s
# A shorter way, but not yet POSIX compliant: IFS=$'\n\b'
# The \b is necessary to prevent \n from being removed.
# Using IFS=$'\n' method might actually work without the \b.
history - list of previous commands
fc -l - list of previous commands
fc -s <#> - re-execute command
!! - previous command
!<#> - execute command # from history
!command - execute most recent 'command'
!string - execute most recent command that starts with 'string' (ie. !c)
!$ - last word of previous line (ie. mkdir test;cd !$ #creates/navigates to test)
!^ - the first argument of previous line (second word, ie. $1)
!* - all the arguments of previous line (i.e $*)
!:2 - the second argument of previous line (can be any number)
!# - the current command line. (ie. 'ls hello !#' expands to 'ls hello ls hello')
!#^ - first argument of current command (also try $, :1, etc.)
^string1^string2 - execute last command and replace string1 with string2
!!:s/string1/string2/ - execute last command and replace string1 with string2
!!:gs/string1/string2/ - execute last command and replace ALL INSTANCES of string1 with string2
esc + . - insert last parameter from last command
adduser <options> <user> - add a user
-m - make a home directory
-d <path> - home directory
-s <path> - shell
-p <pass> - password
-g <group> - primary group
-G <groups> - secondary groups (comma separated list)
(example) useradd -m fred
usermod <options> <user> - modify user or add it to a group
-d <path> - home directory
-s <path> - shell
-p <pass> - password
-g <group> - primary group
-G <groups> - secondary groups (comma separated list)
(example) usermod -G admin bob
userdel -r <user> - delete user, home folder, and mail spool
groupadd <name> - add new group
restorecon /dir - restores selinux labels. use on dirs like /var if you move them.
fixfiles relabel /dir - same as restorecon. worked before.
chmod <perms> <file> - set a file's permissions
-R - recursive
apply to:
u - user
g - group
o - other
a - all
permissions:
r - read
w - write
x - execute
s - SetUID (suid) AND SetGID (sgid)
t - Sticky Bit. Files in a directory with the sticky bit set can only be deleted or renamed by the root user or the owner of the directory.
examples:
u+rwx
g-w
o=rx
+s
u=rwx,g=rx,o=rx (can be comma separated)
octal permissions:
rwx rwx rwx
111 101 101
7 5 5
if four octal digits are used, the first digit is:
0 - no special permissions
1 - sticky bit (do not allow rename or delete, but will allow write if file has +w)
2 - set group ID (other can run as group)
4 - set user ID (other can run as user)
example:
chmod 6755 file (setuid and setgid, looks like: rwsr-sr-x)
if it shows capital 'S' it means it has setid, but not execute permissions (useless)
chmod 1777 file (sticky bit, looks like: rwxrwxrwt)
if it shows capital 'S' it means it has sticky, but not execute permissions
chown - change ownership if files/directories
-R - recursive
examples:
chown -R user:group /this/folder
chown user file
chown :group file (only change group)
add user to sudoers file:
echo '<user> ALL=(ALL) ALL' >> /etc/sudoers
You should use 'visudo' to edit /etc/sudoers instead
passwd <user> - set password
-d - delete password
-e - expire password
-l - lock password
-u - unlock password
-S - status of password
update-grub - updates grub config
shutdown <option> <time> <message>
-h - hault
-r - reboot
-P - poweroff
-c - cancel
time
now - shutsdown now
n - shuts down in n minutes
n:00 - shuts down at n o'clock
telinit <#> - change runlevel
init <#> - change runlevel
runlevels:
0 halt
1 1user text
2 multiuser text
3 multiuser text, network
4 user defined
5 multiuser with x
6 reboot
service <opt> <daemon> <command> - manage daemon
start
stop
restart
status
--status-all
chkconfig <opt> <daemon> <command> - make daemon run on startup
on
off
--list
--level <#s> - specify runlevels command pertains to (ie --level 35 for 3 and 5)
--add <name> - add as service
--del <name> - delete as service
place this at beginning of file to make usable with chkconfig (most are optional):
### BEGIN INIT INFO
# Provides: name
# Required-start: parent-name
# Default-start: runlevels (0 1 2)
# Default-stop: runlevels (0 1 2)
# Description: description
### END INIT INFO
systemctl <opt> <command> <daemon> - manage daemons in systemd
start
stop
reload
restart
status
enable
disable
mask - extreme disable (makes it impossible to start the service; use with caution)
unmask - remove the mask
journalctl -f - follow the systemd event log
systemd-analyze blame - look at individual service boot times
update-rc.d <opt> <daemon> <command> [S|1|2|3|4|5] - old init service control
-n - dry-run
-f - force
defaults - enable the daemon with default startup configurations
enable
disable
<runlevels> - specify runlevels to enable/disable for (ie "23" will specify runlevels 2 and 3)
;read - pause and wait for input
to make a function:
function(){
commands
commands
}
to catch errors:
if ! 'command';then
echo ERROR
else
echo SUCCESS
fi 2>/dev/null
to create exit condition and capture ctrl+c:
# run if user hits control-c
exit_f(){
<commands>
}
# trap keyboard interrupt (control-c)
trap exit_f SIGINT
signals:
SIGINT - ctrl+c
SIGTSTP - ctrl+z
SIGQUIT - quit from keyboard
SIGILL - illegal instruction
SIGHUP - hung process
SIGTERM - kill signal
EXIT - exit of any kind (SHOULD USE THIS ONE)
if [ <?> yada yada ]
-e - if exist
-f - if file
-d - if directory
-r - if readable
-w - if writable
-x - if executable
-b - if block device
-c - if character device (tty)
-p - if pipe
-s - if exist with size greater that 0
-L - if symbolic link (also -h)
-S - if socket
-O - if you are owner
-G - if you are in group
-N - if modified since last read
-z - if zero length
-n - if null
f1 -nt f2 - if newer than
f1 -ot f2 - if older than
f1 -ef f2 - if both links to same file
! - if command produces error (opposite of any test above)
if [ $test1 ];then
do 1
elif [ $test2 ];then
do 2
else
do 3
fi
|| - or
&& - and
! - not
simplified if statement (good for switching debug mode on/off):
a=true
$a && echo "This will echo"
a=false
$a && echo "This will not"
debug=false
$debug && echo "This only echoes if debug mode is ON"
$debug || echo "This only echoes if debug mode is OFF"
() - sub-shell
$() - command substitutions
(()) - arithmetic, "let", used when it contains an 'equals' sign
$(()) - arithmetic expansion, no 'equals' sign enclosed
[] - test
[[]] - test with string comparison
[[ $str =~ $regex ]] - string compare regex
!(not-this) - anything but this, invert
example: ls -d !(Downloads) - list everything EXCEPT Downloads
parallel processing; wait for sub-shells:
wait - do not continue until all sub-shells complete
Example: ( (sleep 2;echo p1) & (sleep 1;echo p2) & wait ); echo DONE
Note: putting everything in a sub-shell suppresses job output.
$0 - Filename of script
$1 - Positional parameter #1
$2 - $9 - Positional parameters #2 - #9
${10} - Positional parameter #10
$# - Number of positional parameters
$* - All the positional parameters (as a single word) *
$@ - All the positional parameters (as separate strings)
${#*} - Number of positional parameters
${#@} - Number of positional parameters
$? - Return value or exit status
$$ - Process ID (PID) of script
$- - Flags passed to script (using set)
$_ - Last argument of previous command
$! - Process ID (PID) of last job run in background
wildcards:
* - anything
? - any single character
[abc] - single character matching a, b, or c
[a-e] - single character matching a, b, c, d, or e
[!a-e] - single character NOT matching a, b, c, d, or e
a+=b - concatenate
let a+=b - add
let a-=b - subtract
let a*=b - multiply
let a/=b - divide
let a++ - increment
let a-- - decrement
expr - resolve math and string expressions. only works with integers.
expr ARG1 < ARG2 - outputs 0 if false, and 1 if true
expr ARG1 \< ARG2 - sometimes you need to escape the operator to avoid conflict with shell operators, including parentheses
+, -, *, /, % - math operators
<, >, =, !=, <=, >=, |, & - other operators
expr match STRING REGEXP - string matching
expr substr STRING POS LENGTH - substring, POS counted from 1
expr index STRING CHARS - find CHARS in STRING
( EXPRESSION ) - parenthetical expression
bc - Precise calculator
-l - use full precision
echo "2/5*(3.14*8)-2" | bc -l | sed 's/0*$//g' - trim trailing zeros
bc -l <<< "2/5*(3.14*8)-2"
while (("$#"));do - cycle parameters through $1 until none left
<commands>
shift
done
continue - put in loop to return to top of loop
case $string1 in
strA | srtB )
commands;;
srtC | strD )
commands;;
*)
commands;;
esac
echo "It's much nicer to use a 'case' than an 'if' for user input."
echo "Do you agree? ";read ans
case $ans in
[yY]|[yY][Ee][Ss])
echo "Then you are wise.";;
*)
echo "I see...";;
esac
# you may want to use "shopt -s nocaseglob" to make case insensitive ("shopt -u nocaseglob" to unset)
# you can also do ${ans,,} for all lowercase, or ${ans^^} for all uppercase
put commands in .bashrc in home dir to run command at login
. <file> OR source <file> - run script such as '.bashrc' as part of current process
bash -x <script> - execute script in debug mode
source <file> - execute file in shell environment (ie. .bashrc)
reset - reset shell defaults
set - set command
-x - set debug mode inside the script (xtrace on)
+x - unset debug mode (xtrace off)
-v - verbose on
+v - verbose off
-e - place at beginning of script to always exit upon error (then use ||true for commands that are allowed to err)
+e - temporarily bypass set -e
-C - enable noclobber
+C - disable noclobber
-H - enable histexpand (i. "!" notation)
+H - disable histexpand (i. "!" notation)
-f - disable pathname expansion, like using asterisk '*' (noglob on)
+f - enable pathname expansion, like using asterisk '*' (noglob off)
-o <option> - enable option name (ie. -o noclobber)
+o <option> - disable option name (ie. +o noclobber)
-o history - enable command history
+o history - disable command history
-o pipefail - enable fail on piped commands
+o pipefail - disable fail on piped commands
-u - do not allow the use of undeclared variables
+u - allow the use of undeclared variables
completion-ignore-case on - tab completion ignores case
set <option_name> - another way to set things
unset <option_name> - another way to unset things
useful examples for set:
set -e; set -o pipefail
setterm -powersave off -blank 0 - make the X Window not blank the screen
setterm -reset - go back to default settings
setterm -msg off - disable printing kernel messages to console
shopt - shell options
-s <opt> - set the option
-u <opt> - unset the option
-s nocaseglob - make the shell case insensitive
tty - print the device file of the current tty
stty - terminal parameters
-a - list all parameters
<param> "<value" - set a param value
<(-)param> - enable/disable a param (ie. ofdel enables, -ofdel disables)
infocmp <term> - get info about terminal (terminfo, termcap)
showkey -a - enter keys to get thir dec/oct/hex value as seen by the terminal (must be root).
terminator - multiple terminals in one window, customizable
tmux - multiplexed terminals in one terminal
ctrl+b - run a command (type the command after)
? - list key bindings
c - create new window
arrow keys - move between panes
0 to 9 - select a window
n - next window
p - previous window
o - next pane
" - split pane top/bottom
% - split pane left/right
x - kill the current pane
& - kill the current window
[ - enter copy mode
] - paste most recent buffer
= - paste from buffer of choice
r - force redraw of screen
: - enter tmux command prompt
alt+<1-5> - select a layout preset
space - next layout preset
alias <com alias>='<com>' - make alias command
\command - run a command ignoring aliases
which -a - all instances of executable in PATH locations
RANGE={1..10} {A..Z} {a..z}
LEADING_ZEROS={000..999}
${var:-value} - make var default to value if not set (temporary; doesn't save the value)
${var:=value} - set var default to value if not set (saves the value)
${var:+message} - if var is set, print message. if var is not set, print nothing
${var:?message} - if var is set, print var. if var is not set, print error with message
SCRIPT=$(readlink -f $0) - the script that is running
SCRIPTPATH="dirname $SCRIPT" - the dir of the script
${#var} - number of characters in var
${var#pattern} - removes shortest possible match from the left
${var##pattern} - removes longest possible match from the left
${var%pattern} - removes shortest possible match from the right
${var%%pattern} - removes longest possible match from the right
${var%?} - ? is single character wild card. To cut 3 characters from the right, use: ${x%???}
examples:
get file extension ${FILE##*.} file.txt -> txt
get file name from path ${FILEPATH##*.} /dir/file.txt -> file.txt
remove file extension ${FILE%.*} file.txt -> file
get directory name from path ${FILEPATH##*.} /dir/file.txt -> /dir
${var/pattern1/pattern2} - substitute pattern1 with pattern2
${var,} - make first character lowercase
${var,,} - make var all lowercase
${var^} - make first character uppercase
${var^^} - make var all uppercase
${var~} - reverse case of first character in var
${var~~} - reverse case of var
${var,pattern} - lowercase first character if matches pattern
${var,,pattern} - lowercase any character if matches pattern
${var^pattern} - uppercase first character if matches pattern
${var^^pattern} - uppercase any character if matches pattern
${var~pattern} - reverse first character if matches pattern
${var~~pattern} - reverse any character if matches pattern
${var:n:m} - substring of var from character n to m (starting at 0; ${var:0:3} = first 3 chars)
${var::m} - blank implies 0 (ie. ${var::4} is the same as ${var:0:4})
${var:n} - cut off n characters from beginning (n=2; hello -> llo)
${var: -n} - cut off all but n characters from end (n=2; hello -> lo)
${var:n: -m} - cut off m characters from end of string starting at n (n=0,m=2; hello -> hel)
${!var} - indirection: if content of var is another variable name, then print the content of other variable
(ie a=b; b=c; echo ${a} #echoes "b"; echo ${!a} #echoes "c")
can also display variable names like: echo ${!BASH*} #echoes name of all vars that begin with BASH
x**y - y is exponent of x
% - remainder ie. $((15%7))
$((2#<binary>)) - define binary number
$((0x<hex>)) - define hex number
export <var>=<value> - set environment variable
declare <option> <var> OR <var=value> - set attributes for a variable (don't use $)
-a - array
-f - function name
-i - integer
-r - readable
-x - make global variable
+<?> - removes attribute
number=$RANDOM ; let "number %= 500" - chooses random number =< 500
while (( $number < 100 )) - sets a floor of 100
set range to 2 to generate binary (true/false). using let "number >>= 14" gives better random distribution
$((RANDOM%range)) - random # up to "range"
string{1,2,3} - expands to: string1 string2 string3
string{01..03} - expands to: string01 string02 string03
cp file.txt{,.old} - expands to: cp file.txt file.txt.old
placing the name of a variable into another variable:
two=2
num=two
echo ${!num} #echoes '2'
formatting 2 digit numbers:
i=2
printf "%02d" $i #echoes '02'
CHAR="[:graph:]";cat /dev/urandom|tr -cd $CHAR|head -c 8 #creates random 8 character password.
array:
list="a b c" - not an array, treated as whole string
array=(a b c) - array, treated as set of items
array=($list) - turn variable into array
${array[2]} - choose item 2 (starting at 0), chooses c in this example
${array[@]} - all items in array form
${array[*]} - all items in
${array[0]:n:m} - string splice (ie. x=(foo bar);echo ${x[1]:0}#echoes "bar";echo ${x[1]:1}#echoes "ar")
syntax - ${array[#]:begin:number} (ie x=(hello);echo {x[0]:0:3}#echoes "hel")
${array[0]:3:2} - specific characters (:3:2 starts at character 3 then goes 2 characters (including 1st) from there, displaying characters 3 and 4.) this can be used to show a range of items. (${list[*]:0:3} #echoes first 3 characters)
(ie x=(foo bar);echo ${x[1]:0:1}#echoes "b";echo ${x[1]:1:1}#echoes "a";echo ${x[1]:2:2}#echoes "r")
${array[@]:0:${#array[@]}-1} - display all items in list except the last one.
${array[@]:n:m} - similar to string splice, but works with array items instead of characters
(ie x=(foo man chu); echo ${x[0]:0:2}#echoes "fo"; echo ${x[@]:0:2}#echoes "foo man")
${#array[*]} - count # of items
${#array[0]} - length of first item
${array[$((RANDOM%num_of_item))]} - choose random item from list
${array[@]^} - make first char in each item uppercase (ie "hi bob" -> "Hi Bob")
unset array[0] - remove array item 0 (no "$" or braces)
list="11 22 33"
if [[ $list =~ $item ]];then echo yes;fi - checks if $item is contained in $list
escape characters:
\\ backslash
\a alert
\b backspace
\c no further output
\e escape
\f form feed
\n new line
\r carriage return
\t horizontal tab
\v vertical tab
\0 null
\0NNN octal number (0-7; 1-3 digits)
\xHH hex byte value (0-F; 1-2 digits)
line endings (EOL, delimiter):
\n \x0a UNIX/Linux
\r\n \x0d\x0a DOS/Windows
\r \x0d MacOS
POSIX character classes (translations, bracketed)
[:alnum:] all letters and digits
[:alpha:] all letters
[:blank:] all horizontal whitespace
[:cntrl:] all control characters
[:digit:] all digits
[:graph:] all printable characters, not including space
[:lower:] all lower case letters
[:print:] all printable characters, including space
[:punct:] all punctuation characters
[:space:] all horizontal or vertical whitespace
[:upper:] all upper case letters
[:xdigit:] all hexadecimal digits
updating a line of text (progress bar):
i=0
while (( $i <= 5 ));do
string=`echo -n "Progress: $i%"`
count=${#string}
echo -n $string
sleep 1
printf '%0.s\x08' $(seq 1 $count)
let i++
done && echo Complete
POWER SAVING:
apt-get install laptop-mode-tools
sudo vim /etc/laptop-mode/conf.d/cpufreq.conf
CONTROL_CPU_FREQUENCY=0
sudo service laptop-mode restart
selinux - see file "selinux"
iptables - see file "iptables"
samba (smbd/netbios/nmbd) - see file "samba"
nfs - see file "nfs"
cisco - see file "cisco"
bind (dns) - see file "bind"
gdb - see file "gdb"
nmap - see file "nmap"
regex (regular expression) - see file "regex"
ssh - see file "ssh"
tor - see file "tor"
tsocks - see file "tor"
zenity - see file "zenity"
wine - see file "wine"
unicode - see file "unicode"
ftp - see file "ftp"
ldap - see file "ldap"
nis - see file "ldap"
html - see file "html"
grub - see file "grub"
apache (httpd) - see file "apache"
cups/printing/lpr/lpd - see file "cups"
at (atd) - see file "at"
cron (crond) - see file "cron"
raid/mdadm - see file "raid"