CLI Magic: I Didn’t Know That !

ID N0WHERE:21733
Type n0where
Reporter N0where
Modified 2014-08-10T01:27:23


Command Editing Shortcuts

Ctrl + a – go to the start of the command line
Ctrl + e – go to the end of the command line
Ctrl + k – delete from cursor to the end of the command line
Ctrl + u – delete from cursor to the start of the command line
Ctrl + w – delete from cursor to start of word (i.e. delete backwards one word)
Ctrl + y – paste word or text that was cut using one of the deletion shortcuts (such as the one above) after the cursor
Ctrl + xx – move between start of command line and current cursor position (and back again)
Alt + b – move backward one word (or go to start of word the cursor is currently on)
Alt + f – move forward one word (or go to end of word the cursor is currently on)
Alt + d – delete to end of word starting at cursor (whole word if cursor is at the beginning of word)
Alt + c – capitalize to end of word starting at cursor (whole word if cursor is at the beginning of word)
Alt + u – make uppercase from cursor to end of word
Alt + l – make lowercase from cursor to end of word
Alt + t – swap current word with previous
Ctrl + f – move forward one character
Ctrl + b – move backward one character
Ctrl + d – delete character under the cursor
Ctrl + h – delete character before the cursor
Ctrl + t – swap character under cursor with the previous one

Command Recall Shortcuts

Ctrl + r – search the history backwards
Ctrl + g – escape from history searching mode
Ctrl + p – previous command in history (i.e. walk back through the command history)
Ctrl + n – next command in history (i.e. walk forward through the command history)
Alt + . – use the last word of the previous command

Command Control Shortcuts

Ctrl + l – clear the screen
Ctrl + s – stops the output to the screen (for long running verbose command)
Ctrl + q – allow output to the screen (if previously stopped using command above)
Ctrl + c – terminate the command
Ctrl + z – suspend/stop the command

Bash Bang (!)

!! – run last command
!blah – run the most recent command that starts with ‘blah’ (e.g. !ls)
!blah:p – print out the command that !blah would run (also adds it as the latest command in the command history)
!$ – the last word of the previous command (same as Alt + .)
!$:p – print out the word that !$ would substitute
! – the previous command except for the last word (e.g. if you type ‘find some_file.txt /‘, then ! would give you ‘find some_file.txt‘)
!:p – print out what ! would substitute
!:- – Insert the last command without the last argument (bash)


sudo !! – Run the last command as root
^foo^bar – Runs previous command but replacing
ctrl-x e – Rapidly invoke an editor to write a long, complex, or tricky command
‘ALT+.’ or ‘<ESC> .’ – Place the argument of the most recent command on the shell
fc – Rapidly invoke an editor to write a long, complex, or tricky command
bind -P | grep -v “is not” | sed -e ‘s/can be found on/:/’ | column -s: -t – List all bash shortcuts


currently mounted filesystems in nice layout

mount | column -t

column -t /proc/mounts – currently mounted filesystems in nice layout
curl – Get your external IP address
dig +short – Get your external IP address
man ascii – Quick access to the ascii table.
dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp – output your microphone to a remote computer’s speaker
arecord -f dat | ssh -C user@host aplay -f dat – output your microphone to a remote computer’s speaker
sshfs name@server:/path/to/folder /path/to/mount/point – Mount folder/filesystem through SSH
mount -t tmpfs tmpfs /mnt -o size=1024m – Mount a temporary ram partition
wget –random-wait -r -p -e robots=off -U mozilla – Download an entire website
wget –recursive –no-clobber –page-requisites –html-extension –convert-links –restrict-file-names=windows –domains –no-parent – – Download an entire website
curl -u user:pass -d status=”Tweeting from the shell” – twitter via curl
“ssh user@host cat /path/to/remotefile | diff /path/to/localfile -” – Compare a remote file with a local file
time read (ctrl-d to stop) – A very simple and useful stopwatch
ssh -t reachable_host ssh unreachable_host – SSH connection through host in the middle
less +F somelogfile – Make ‘less’ behave like ‘tail -f’
disown -a && exit – Close shell keeping all subprocess running
while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done & – Put a console clock in top right corner
net rpc shutdown -I ipAddressOfWindowsPC -U username%password – Shutdown a Windows machine from Linux
history | awk ‘{a[$2]++}END{for(i in a){print a[i] ” ” i}}’ | sort -rn | head – List of commands you use most often
ping -i 60 -a IP_address – Set audible alarm when an IP address comes online
getconf LONG_BIT – 32 bits or 64 bits?
mv filename.{old,new} – quickly rename a file
ps aux | sort -nk +4 | tail – Display the top ten running processes – sorted by memory usage
pushd /tmp – Push your present working directory to a stack that you can pop later – popd retreives it
some_very_long_and_complex_command # label – Easy and fast access to often executed commands that are very long and complex.
lsof -i – Watch Network Service Activity in Real-time
lsof -P -i -n – Show apps that use internet connection at the moment. (Multi-Language)
netstat -ntauple – Watch Network Service Activity in Real-time
echo “!!” > – Create a script of the last executed command
rm !(.foo|.bar|.baz) – Delete all files in a folder that don’t match a certain file extension
rm -f !(survivior.txt) – Remove all but one specific file
find . ! -name <FILENAME> -delete – Remove everything except that file
nc -v -l 80 < file.ext – Sharing file through http 80 port
awk ‘/start_pattern/,/stop_pattern/’ file.txt – Display a block of text with AWK
sed -n /start_pattern/,/stop_pattern/p file.txt – Display a block of text with AWK
ifconfig | convert label:@- ip.png – save command output to image
fuser -k filename – Kills a process that is locking a file.
awk ‘!x[$0]++’ <file> – Remove duplicate entries in a file without sorting.
cat /etc/issue – Display which distro is installed
ssh-copy-id username@hostname – Copy your SSH public key on a remote machine for passwordless login – the easy way
cat ~/.ssh/ | ssh user@machine “mkdir ~/.ssh; cat >> ~/.ssh/authorized_keys” – Copy your ssh public key to a server from a machine that doesn’t have ssh-copy-id
wget -qO – “” | tar zxvf – – Extract tarball from internet without local saving
mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile <output-file> <input-file> – Rip audio from a video file.
rename ‘y/ //’ * – replace spaces in filenames with underscores
strace -ff -e trace=write -e write=1,2 -p SOME_PID – intercept stdout/stderr of another process
strace -ff -e write=1,2 -s 1024 -p PID 2>&1 | grep “^ |” | cut -c11-60 | sed -e ‘s/ //g’ | xxd -r -p – intercept stdout/stderr of another process
strace -e write=1,2 -p $PID 2>&1 | sed -un “/^ |/p” | sed -ue “s/^.\{9\}\(.\{50\}\).\+/\1/g” -e ‘s/ //g’ | xxd -r -p – intercept stdout/stderr of another process or disowned process
pv sourcefile > destfile – Copy a file using pv and watch its progress
mkdir /home/foo/doc/bar && cd $
– mkdir & cd into it as single command
mkdir -p a/long/directory/path – Make directory including intermediate directories
ss -p – Show apps that use internet connection at the moment. (Multi-Language)
^Z $bg $disown – Suspend it, send it to the background, then disown it
strings /dev/urandom | grep -o ‘[[:alnum:]]’ | head -n 30 | tr -d ‘\n’; echo – Generate a random password 30 characters long
grep -RnisI <pattern> * – Search for a <pattern> string inside all files in the current directory
ffmpeg -f x11grab -r 25 -s 800×600 -i :0.0 /tmp/outputFile.mpg – Record a screencast and convert it to an mpeg
date -d@1234567890 – Convert seconds to human-readable format
watch -n 1 mysqladmin –user=<user> –password=<password> processlist – Monitor the queries being run by MySQL
du -s * | sort -n | tail – Get the 10 biggest files/folders for the current direcotry
gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=OUTPUT.pdf -c .setpdfwrite -f INPUT.pdf – Remove security limitations from PDF documents using ghostscript
dd if=/dev/zero of=/dev/null bs=1M count=32768 – Processor / memory bandwidthd? in GB/s
mount /path/to/file.iso /mnt/cdrom -oloop – Mount a .iso file in UNIX/Linux
ssh -MNf <user>@<host> – Create a persistent connection to a machine
chmod –reference file1 file2 – Makes the permissions of file2 the same as file1
ps awwfux | less -S – Show a 4-way scrollable process tree with full details.
ssh -t remote_host screen -r – Attach screen over ssh
ssh -t /usr/bin/screen -xRR – Attach screen over ssh
echo “rm -rf /unwanted-but-large/folder” | batch – Run a command only when load average is below a certain threshold
timeout 5s COMMAND – Start COMMAND, and kill it if still running after 5 seconds
cat /dev/urandom | hexdump -C | grep “ca fe” – just fucking awesome, does nothing, screensaver
find . -type d -empty -delete – Recursively remove all empty directories
find . -empty -type d -exec rmdir {} + – Recursively remove all empty directories
find . -type d -empty -delete – Recursively remove all empty directories
cp file.txt{,.bak} – Create a quick back-up copy of a file
sed -n 5p <file> – To print a specific line from a file
tar -tf <file.tar.gz> | xargs rm -r – Remove all files previously extracted from a tar(.gz) file.
% screen -r someuser/ – Share a terminal screen with others
script -qf | tee >(nc -kl 5000) >(nc -kl 5001) >(nc -kl 5002) – Broadcast your shell thru ports 5000, 5001, 5002 …
bash -i 2>&1 | tee /dev/stderr | nc -l 5000 – – Broadcast your shell thru ports 5000, 5001, 5002
script -qf >(nc -ub 5000) – Broadcast your shell thru ports 5000, 5001, 5002
script -qf | tee >(nc -l -p 5000) — Broadcast your shell thru ports 5000, 5001, 5002
diff <(lsof -p <PID>) <(sleep 10; lsof -p <PID>) – snapshot of the open files for a PID
curl – Nice weather forecast on your shell
until !!; do :; done – Retry the previous command until it exits successfully
ls -d
/ – List only the directories
lsof -i tcp:80 – which program is this port belongs to ?
watch -n 1 ‘echo “obase=2;date +%s” | bc’ – Binary Clock
wget -r -l1 –no-parent -nH -nd -P/tmp -A”.gif,.jpg” – Download all images from a site
grep ^Dirty /proc/meminfo – Find out how much data is waiting to be written to disk
for I in $(mysql -e ‘show databases’ -s –skip-column-names); do mysqldump $I | gzip > “$I.sql.gz”; done – Backup all MySQL Databases to individual files
sudo find / -mmin 60 -type f – Find files that have been modified on your system in the past 60 minutes
diff <(cd dir1 && find | sort) <(cd dir2 && find | sort) – Compare two directory trees.
find ./ -type f -exec chmod 644 {} \; – Recursively change permissions on files, leave directories alone.
find . -type f -newermt “2010-01-01” ! -newermt “2010-06-01″ – find files in a date range
[enter]~? – Control ssh connection
lsof -P -i -n | cut -f 1 -d ” “| uniq | tail -n +2 – Show apps that use internet connection at the moment.
grep . filename > newfilename – Remove blank lines from a file using grep and save output to new file
history -d – delete a line from your shell history
echo ${SSH_CLIENT%% } – Get the IP of the host your coming from when logged in remotely
lshw -html > hardware.html – Create a nifty overview of the hardware in your computer
find / -type f -size +500M – find all file larger than 500M
lsof -Pan -i tcp -i udp – Lists all listening ports together with the PID of the associated process
yes | pv | ssh $host “cat > /dev/null” – live ssh network throughput test
ssh remotehost ‘dpkg –get-selections’ | dpkg –set-selections && dselect install – Tell local Debian machine to install packages used by remote Debian machine
grep -Fx -f file1 file2 – intersection between two files
killall -STOP/-CONT -m firefox – Manually Pause/Unpause Firefox Process with POSIX-Signals – Zero CPU load.
DISPLAY=:0.0 import -window root /tmp/shot.png – Take screenshot through SSH
( command & ) – A child process which survives the parent’s death (for sure)
( ( sleep 2h; your-command your-args ) & ) – Schedule a script or command in x num hours, silently run in the background even if logged out
lsof -c dhcpd – List all files opened by a particular command
tar –create –file – –posix –gzip — <dir> | openssl enc -e -aes256 -out <file> – Encrypted archive with openssl and tar
openssl enc -d -aes256 -in <file> | tar –extract –file – –gzip – Decrypt Encrypted archive with openssl and tar
file -s /dev/sd
– Use file(1) to view device information
sl – pure fun
nc -l -p 2000 -c “nc 3000” – Create a single-use TCP (or UDP) proxy – Redirect the local port 2000 to the remote port 3000. The same but UDP: nc -u -l -p 2000 -c “nc -u 3000”
dd if=/dev/sda | tee >(dd of=/dev/sdb) | dd of=/dev/sdc – Duplicate several drives concurrently
grep -lir “some text” * – find files containing text
ln -nsf <TARGET> <LINK> – Repoint an existing symlink to a new location
rename ‘y/A-Z/a-z/’ * – convert filenames in current directory to lowercase
tail -10000 /var/log/nginx/access.log | awk ‘{print $1}’ | sort | uniq -c | sort -n | tail – Analyse an Apache access log for the most common IP addresses
udo cpulimit -p pid -l 50 – Limit the cpu usage of a process
ls -hog – ls -hog –> a more compact ls -l
sed ‘999995,1000005!d’ < my_massive_file – Efficiently print a line deep in a huge log file
wall <<< “Broadcast This” – send a circular
taskset -c 0 your_command – Start a command on only one CPU core
autossh -M50000 -t ‘screen -raAd mysession’ – Have an ssh session open forever
find -L /path/to/check -type l -delete – Find broken symlinks and delete them
sed -i <file> -re ‘<start>,<end>d’ – Remove a range of lines from a file
lsof -i -P | grep -i “listen” – List all open ports and their owning executables
aptitude purge ‘~c’ – Purge configuration files of removed packages on debian based systems
lsof -Pni4 | grep LISTEN – check open ports
sudo dd if=/dev/zero of=/swapfile bs=1024 count=1024000;sudo mkswap /swapfile; sudo swapon /swapfile – create an emergency swapfile when the existing swap space is getting tight
mv $1 $2 && ln -s $2/$(basename $1) $(dirname $1) – Relocate a file or directory, but keep it accessible on the old location throug a simlink.
rsync –rsync-path ‘sudo rsync’ username@source:/folder/ /local/ – Rsync remote data as root using sudo
unset HISTFILE – disable history for current shell session
arch – Check if system is 32bit or 64bit
namei -m $(pwd) – Show permissions of current directory and all directories upwards to /
fuser -v 80/tcp – Show what PID is listening on port 80 on Linux
find . -type f -printf ‘%TY-%Tm-%Td %TT %p\n’ | sort – Find the most recently changed files (recursively)
netstat -lantp | grep ESTABLISHED |awk ‘{print $5}’ | awk -F: ‘{print $1}’ | sort -u – All IP connected to my host
wget http://URL/FILE.tar.gz -O – | tar xfz – – Download a file and uncompress it while it downloads
dd if=/dev/mem bs=1k skip=768 count=256 2>/dev/null | strings -n 8 – Display BIOS Information
grep ‘test’ somefile | grep -vE ‘(error|critical|warning)’ – grep -v with multiple patterns.
who -b – Find last reboot time
lsof +p xxxx – List the files any process is using
du -hs / | sort -hr | head – List 10 largest directories in current directory
openssl rand -hex 6 | sed ‘s/\(..\)/\1:/g; s/.$//’ – Generate a Random MAC address
pwgen -Bs 10 1 – generate random password
Ctrl+S Ctrl+Q – Ctrl+S Ctrl+Q terminal output lock and unlock
ps -fC PROCESSNAME – Search for a process by name
read -s -p”Password: ” USER_PASSWORD_VARIABLE; echo – Ask for a password, the passwd-style
watch vmstat -sSM – monitor memory usage
echo “uptime” | tee >(ssh host1) >(ssh host2) >(ssh host3) – run command on a group of nodes in parallel
pkill -x firefox – kill process by name
rsync -az /home/user/test user@sshServer:/tmp/ – move a lot of files over ssh
watch -n 1 “netstat -tpanl | grep ESTABLISHED” – Monitor TCP opened connections
watch “ss -nat | awk ‘”‘{print $1}'”‘ | sort | uniq -c” – Monitor TCP opened connections
netstat -ntu | awk ‘{print $5}’ | cut -d: -f1 | sort | uniq -c | sort -n – Number of open connections per ip.
sudo dmidecode –type 17 | more – Check Ram Speed and Type in Linux
rsync –partial –progress –rsh=ssh SOURCE DESTINATION – Resume aborted scp file transfers
ssh -t remotebox “tail -f /var/log/remote.log” – tail a log over ssh
cmp file1 file2 – Compare copies of a file with md5
arp-scan -I eth0 – Find all active ip’s in a subnet
dmidecode -t bios – Display BIOS Information
echo -ne “<shellcode>” | x86dis -e 0 -s intel – Disassemble some shell code
ps aux –sort=%mem,%cpu – Sort all running processes by their memory & CPU usage
su — user – Change user, assume environment, stay in current dir
hdparm -t /dev/sda – Testing hard disk reading speed
sudo aptitude purge dpkg –get-selections | grep deinstall | awk ‘{print $1}’ – Purge configuration files of removed packages on debian based systems
hwinfo –block –short – Show all detected mountable Drives/Partitions/BlockDevices
for i in
.html ; do mv $i ${i%.html}.htm ; done – change extension
sudo tune2fs -l $(df -h / |(read; awk ‘{print $1; exit}’)) | grep -i created – Show how old your linux OS installtion is
ps -eo pid,lstart,cmd – Discover the process start time
screen -D -R – Automatically find and re-attach to a detached screen session
dmidecode | grep Product – what model of computer I’m using ?
while inotifywait -e modify /tmp/myfile; do firefox; done – Run a command when a file is changed
while true ; do nc -l 80 < index.html ; done – One command line web server on port 80 using nc (netcat)
apt-get install ssh root@host_you_want_to_clone “dpkg -l | grep ii” | awk ‘{print $2}’ – “Clone” a list of installed packages from one Debian/Ubuntu Server to another
ssh user@remote-host “DISPLAY=:0.0 import -window root -format png -“|display -format png – – Remote screenshot
dd if=/path/inputfile | pv | dd of=/path/outpufile – Start dd and show progress every X seconds
kill -9 -1 – kill all process that belongs to you
sudo chattr +i <file> – Make a file not writable / immutable by root
sed -n ‘4p’ – Print just line 4 from a textfile
find . -iname ‘.jpg’ -exec echo ‘<img src=”{}”>’ \; > gallery.html – Quick HTML image gallery from folder contents
dd if=/dev/sda | ssh user@server ‘dd of=sda.img’ – Backup a local drive into a file on the remote host via ssh
find /proc -user myuser -maxdepth 1 -type d -mtime +7 -exec basename {} \; | xargs kill -9 – Kill processes that have been running for more than a week
rename ‘s/^/prefix/’ * – Add prefix onto filenames
grep –color=auto -iRnH “$search_word” $directory – Grep for word in directory (recursive)
find /path/to/dir -type f -print0 | xargs -0 rm – Optimal way of deleting huge numbers of files
<Return>~. – Kill a broken ssh connection
tar xfz filename.tar.gz -C PathToDirectory – Redirect tar extract to another directory
pkill -KILL -u username – force a userid to log out of a Linux host, by killing all processes owned by the user, including login shells
lsmac() { ifconfig -a | sed ‘/eth\|wl/!d;s/ Link.
HWaddr//’ ; } – List your MACs address
MIN=10;for ((i=MIN60;i>=0;i–));do echo -ne “\r$(date -d”0+$i sec” +%H:%M:%S)”;sleep 1;done – Countdown Clock
curl -I http://localhost – Send an http HEAD request w/curl
ssh-keygen -l -f ~/.ssh/known_hosts – View ~/.ssh/known_hosts key information
kill -9 ps -xaw -o state -o ppid | grep Z | grep -v PID | awk ‘{print $2}’ – Kill all Zombie processes (Guaranteed!)
for i in seq 0 100;do timeout 6 dialog –gauge “Install…” 6 40 “$i”;done – pretend to be busy in office to enjoy a cup of coffee
:> file – Empty a file
find -type f -exec mv {} . \; – Move items from subdirectories to current directory
pv /dev/zero|ssh $host ‘cat > /dev/null’ – live ssh network throughput test
sed -i ‘/myexpression/d’ /path/to/file.txt – Remove lines that contain a specific pattern($1) from file($2).
arecord -q -f cd -r 44100 -c2 -t raw | lame -S -x -h -b 128 – date +%Y%m%d%H%M.mp3 – Record microphone input and output to date stamped mp3 file
touch {1..10}.txt – Create a bunch of dummy files for testing
echo &lt; /dev/urandom tr -dc _A-Z-a-z-0-9 | head -c6 – Generate Random Passwords
!:n – Get the Nth argument of the last command (handling spaces correctly)
find / -type f -size +500M -size -1G – Find all files larger than 500M and less than 1GB
strace -ff -e write=1,2 -s 1024 -p PID 2>&1 | grep “^ |” | cut -c11-60 | sed -e ‘s/ //g’ | xxd -r -p – intercept stdout/stderr of another process
dmidecode -t 17 | awk -F”:” ‘/Speed/ { print $2 }’ – See your current RAM frequency
taskset -cp <core> <pid> – Change proccess affinity.
split -b 19m file Nameforpart – Split File in parts – cat Nameforpartaa Nameforpartab Nameforpartac >> File
tail -fs 1 somefile – Tail -f at your own pace
iptables -t nat -A PREROUTING -p tcp –dport [port of your choosing] -j REDIRECT –to-ports 22 – Redirect incoming traffic to SSH, from a port of your choosing
ls -d
/ – list directories only
dd if=<device> | pv | nc <target> <port> – Compress and store the image of a disk over the network – receiving end : nc -l -p <port> | 7z a <filename> -si -m0=lzma2 -mx=9 -ms=on
touch –date “2010-01-05” /tmp/filename – Change/Modify timestamp
!! – Use result of the last command
dmesg -xT -l err,crit,emerg – Show errors in the kernel ring buffer
find public_html/ -type d -exec chmod 755 {} +
rename ‘s/foo/bar/g’ ./* – Rename all files which contain the sub-string ‘foo’, replacing it with ‘bar’
ip route | awk ‘/default/{print $3}’ – Find default gateway
apt-file find bin/programname – search ubuntu packages to find which package contains the executable program programname
awk ‘/start_pattern/,/stop_pattern/’ file.txt – Display a block of text with AWK
echo $(shuf -i 1-49 | head -n6 | sort -n) – lotto generator
mkisofs -o XYZ.iso XYZ/ – create iso image from a directory
eject /dev/sdb; sleep 1; eject -t /dev/sdb – Remount a usb disk in Gnome without physically removing and reinserting
netstat -lantp | grep -i stab | awk -F/ ‘{print $2}’ | sort | uniq – Show apps that use internet connection at the moment.
ssh -f user@remote.ip DISPLAY=:0.0 smplayer movie.avi – Start an X app remotely
ssh -t user@host screen -x <screen name> – ssh and attach to a screen in one line.
ls -1t | head -n10 – find the 10 latest (modified) files
dd if=/dev/sda5 bs=2048 conv=noerror,sync | gzip -fc | lftp -u user,passwd domain.tld -e “put /dev/stdin -o backup-$(date +%Y%m%d%H%M).gz; quit” – Backup sda5 partition to ftp ( using pipes and gziped backup )
for h in host1 host2 host3 host4 ; { scp file user@$h:/destination_path/ ; } – Copy something to multiple SSH hosts with a Bash loop
curl -C – -o partially_downloaded_file ‘’ – resume download using curl
watch ifconfig eth0 – Watch Data Usage on eth0
ssh -CNL 3306:localhost:3306 – Create an SSH tunnel for accessing your remote MySQL database with a local port
^u – Type ^u at password prompt to clear a mistyped password.
lsof -Pnl +M -i4 – List open IPv4 connections
wget -b – background a wget download
chattr -R +i dirname – Protect directory from an overzealous rm -rf *
<Esc> _ – Place the argument of the most recent command on the shell
find directory/ -mtime 0 -type f – Find today created files
ssh [user]@[address] “mpg321 -” < [file].mp3 – Stream audio over ssh
ls -1 /lib/modules – Lists installed kernels
mount -o loop -t iso9660 my.iso /mnt/something – mount an iso