-
Notifications
You must be signed in to change notification settings - Fork 0
/
oneliners.txt
3058 lines (3057 loc) · 107 KB
/
oneliners.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Run the last command as root
$ sudo !!
copy
Serve current directory tree at http://$HOSTNAME:8000/
$ python -m SimpleHTTPServer
copy
Runs previous command but replacing
$ ^foo^bar
copy
Rapidly invoke an editor to write a long, complex, or tricky command
$ ctrl-x e
copy
Place the argument of the most recent command on the shell
$ 'ALT+.' or '<ESC> .'
copy
currently mounted filesystems in nice layout
$ mount | column -t
copy
Salvage a borked terminal
$ reset
copy
Get your external IP address
$ curl ifconfig.me
copy
Execute a command at a given time
$ echo "ls -l" | at midnight
copy
Quick access to the ascii table.
$ man ascii
copy
output your microphone to a remote computer's speaker
$ dd if=/dev/dsp | ssh -c arcfour -C username@host dd of=/dev/dsp
copy
type partial command, kill this command, check something you forgot, yank the command, resume typing.
$ <ctrl+u> [...] <ctrl+y>
copy
Query Wikipedia via console over DNS
$ dig +short txt <keyword>.wp.dg.cx
copy
Mount folder/filesystem through SSH
$ sshfs name@server:/path/to/folder /path/to/mount/point
copy
Mount a temporary ram partition
$ mount -t tmpfs tmpfs /mnt -o size=1024m
copy
Download an entire website
$ wget --random-wait -r -p -e robots=off -U mozilla http://www.example.com
copy
Clear the terminal screen
$ ctrl-l
copy
Compare a remote file with a local file
$ ssh user@host cat /path/to/remotefile | diff /path/to/localfile -
copy
SSH connection through host in the middle
$ ssh -t reachable_host ssh unreachable_host
copy
Update twitter via curl
$ curl -u user:pass -d status="Tweeting from the shell" http://twitter.com/statuses/update.xml
copy
A very simple and useful stopwatch
$ time read (ctrl-d to stop)
copy
Put a console clock in top right corner
$ while sleep 1;do tput sc; tput cup 0 $(($( tput cols)-29));date; tput rc;done &
copy
Make 'less' behave like 'tail -f'.
$ less +F somelogfile
copy
Close shell keeping all subprocess running
$ disown -a && exit
copy
Watch Star Wars via telnet
$ telnet towel.blinkenlights.nl
copy
32 bits or 64 bits?
$ getconf LONG_BIT
copy
List of commands you use most often
$ history | awk '{a[$2]++}END{for(i in a){print a[i] " " i}}' | sort -rn | head
copy
Simulate typing
$ echo "You can simulate on-screen typing just like in the movies" | pv -qL 10
copy
Set audible alarm when an IP address comes online
$ ping -i 60 -a IP_address
copy
Reboot machine when everything is hanging
$ <alt> + <print screen/sys rq> + <R> - <S> - <E> - <I> - <U> - <B>
copy
quickly rename a file
$ mv filename.{old,new}
copy
Display the top ten running processes - sorted by memory usage
$ ps aux | sort -nk +4 | tail
copy
Delete all files in a folder that don't match a certain file extension
$ rm !(*.foo|*.bar|*.baz)
copy
Push your present working directory to a stack that you can pop later
$ pushd /tmp
copy
Create a script of the last executed command
$ echo "!!" > foo.sh
copy
Watch Network Service Activity in Real-time
$ lsof -i
copy
Easy and fast access to often executed commands that are very long and complex.
$ some_very_long_and_complex_command # label
copy
escape any command aliases
$ \[command]
copy
Show apps that use internet connection at the moment. (Multi-Language)
$ lsof -P -i -n
copy
diff two unsorted files without creating temporary files
$ diff <(sort file1) <(sort file2)
copy
Reuse all parameter of the previous command line
$ !*
copy
Backticks are evil
$ echo "The date is: $( date +%D)"
copy
Sharing file through http 80 port
$ nc -v -l 80 < file.ext
copy
Show File System Hierarchy
$ man hier
copy
Display a block of text with AWK
$ awk '/start_pattern/,/stop_pattern/' file.txt
copy
Set CDPATH to ease navigation
$ CDPATH=:..:~:~/projects
copy
save command output to image
$ ifconfig | convert label:@- ip.png
copy
Add Password Protection to a file your editing in vim.
$ vim -x <FILENAME>
copy
Remove duplicate entries in a file without sorting.
$ awk '!x[$0]++' <file>
copy
Copy your SSH public key on a remote machine for passwordless login - the easy way
$ ssh-copy-id username@hostname
copy
Find Duplicate Files (based on size first, then MD5 hash)
$ find -not -empty -type f -printf "%s
" | sort -rn | uniq -d | xargs -I{} -n1 find -type f -size {}c -print0 | xargs -0 md5sum | sort | uniq -w32 --all-repeated=separate
copy
Kills a process that is locking a file.
$ fuser -k filename
copy
Insert the last command without the last argument (bash)
$ !:-
copy
python smtp server
$ python -m smtpd -n -c DebuggingServer localhost:1025
copy
Display which distro is installed
$ cat /etc/issue
copy
Find the process you are looking for minus the grepped one
$ ps aux | grep [p]rocess-name
copy
Extract tarball from internet without local saving
$ wget -qO - "http://www. tarball.com/ tarball.gz" | tar zxvf -
copy
Copy your ssh public key to a server from a machine that doesn't have ssh-copy-id
$ cat ~/. ssh/id_rsa.pub | ssh user@machine "mkdir ~/. ssh; cat >> ~/. ssh/authorized_keys"
copy
Matrix Style
$ tr -c "[:digit:]" " " < /dev/urandom | dd cbs=$COLUMNS conv=unblock | GREP_COLOR="1;32" grep --color "[^ ]"
copy
replace spaces in filenames with underscores
$ rename 'y/ /_/' *
copy
Rip audio from a video file.
$ mplayer -ao pcm -vo null -vc dummy -dumpaudio -dumpfile <output-file> <input-file>
copy
Google Translate
$ translate(){ wget -qO- "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&q=$1&langpair=$2|${3:-en}" | sed 's/.*"translatedText":"\([^"]*\)".*}/\1
/'; }
copy
Inserts the results of an autocompletion in the command line
$ ESC *
copy
Rapidly invoke an editor to write a long, complex, or tricky command
$ fc
copy
A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram
$ sudo dd if=/dev/mem | cat | strings
copy
Graphical tree of sub-directories
$ ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/ /' -e 's/-/|/'
copy
intercept stdout/stderr of another process
$ strace -ff -e trace=write -e write=1,2 -p SOME_PID
copy
Copy a file using pv and watch its progress
$ pv sourcefile > destfile
copy
Define a quick calculator function
$ ? () { echo "$*" | bc -l; }
copy
Create a CD/DVD ISO image from disk.
$ readom dev=/dev/scd0 f=/path/to/image.iso
copy
mkdir & cd into it as single command
$ mkdir /home/foo/doc/bar && cd $_
copy
Create a pdf version of a manpage
$ man -t manpage | ps2pdf - filename.pdf
copy
Stream YouTube URL directly to mplayer.
$ i="8uyxVmdaJ-w";mplayer -fs $(curl -s "http://www.youtube.com/get_video_info?&video_id=$i" | echo -e $(sed 's/%/\\x/g;s/.*\(v[0-9]\.lscache.*\)/http:\/\/\1/g') | grep -oP '^[^|,]*')
copy
Make directory including intermediate directories
$ mkdir -p a/long/directory/path
copy
Easily search running processes (alias).
$ alias 'ps?'='ps ax | grep '
copy
Multiple variable assignments from command output in BASH
$ read day month year <<< $(date +'%d %m %y')
copy
Remove all but one specific file
$ rm -f !(survivior.txt)
copy
git remove files which have been deleted
$ git add -u
copy
Edit a file on a remote host using vim
$ vim scp://username@host//path/to/somefile
copy
Job Control
$ ^Z $bg $disown
copy
Generate a random password 30 characters long
$ s trings /dev/urandom | grep -o '[[:alnum:]]' | head -n 30 | tr -d '
'; echo
copy
Show apps that use internet connection at the moment. (Multi-Language)
$ ss -p
copy
Graph # of connections for each hosts.
$ netstat -an | grep ESTABLISHED | awk '{ print $5}' | awk -F: '{ print $1}' | sort | uniq -c | awk '{ printf("%s\t%s\t",$2,$1) ; for (i = 0; i < $1; i++) { printf("*")}; print "" }'
copy
Record a screencast and convert it to an mpeg
$ ffmpeg -f x11grab -r 25 -s 800x600 -i :0.0 /tmp/outputFile.mpg
copy
Monitor progress of a command
$ pv access.log | gzip > access.log.gz
copy
Search for a <pattern> string inside all files in the current directory
$ grep -RnisI <pattern> *
copy
Monitor the queries being run by MySQL
$ watch -n 1 mysqladmin --user=<user> --password=<password> processlist
copy
Get the 10 biggest files/folders for the current direcotry
$ du -s * | sort -n | tail
copy
Show numerical values for each of the 256 colors in bash
$ for code in {0..255}; do echo -e "\e[38;05;${ code}m $ code: Test"; done
copy
Recursively remove all empty directories
$ find . -type d -empty -delete
copy
Display a cool clock on your terminal
$ watch -t -n1 "date +%T|figlet"
copy
Convert seconds to human-readable format
$ date -d@1234567890
copy
Nice weather forecast on your shell
$ curl wttr.in/seville
copy
Check your unread Gmail from the command line
$ curl -u username:password --silent "https://mail.google.com/mail/feed/atom" | tr -d '
' | awk -F '<en try>' '{for (i=2; i<=NF; i++) {print $i}}' | sed -n "s/<title>\(.*\)<\/title.*name>\(.*\)<\/name>.*/\2 - \1/p"
copy
Search commandlinefu.com from the command line using the API
$ cmdfu(){ curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; }
copy
Processor / memory bandwidthd? in GB/s
$ dd if=/dev/zero of=/dev/null bs=1M count=32768
copy
pretend to be busy in office to enjoy a cup of coffee
$ cat /dev/urandom | hexdump -C | grep "ca fe"
copy
Makes the permissions of file2 the same as file1
$ chmod --reference file1 file2
copy
Remove security limitations from PDF documents using ghostscript
$ gs -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -sOutputFile=OUTPUT.pdf -c .setpdfwrite -f INPUT.pdf
copy
Send pop-up notifications on Gnome
$ notify-send ["<title>"] "<body>"
copy
(Debian/Ubuntu) Discover what package a file belongs to
$ dpkg -S /usr/bin/ls
copy
Mount a .iso file in UNIX/Linux
$ mount /path/to/file.iso /mnt/cdrom -oloop
copy
Remove a line in a text file. Useful to fix
$ ssh-keygen -R <the_offending_host>
copy
To print a specific line from a file
$ sed -n 5p <file>
copy
Open Finder from the current Terminal location
$ open .
copy
Create a persistent connection to a machine
$ ssh -MNf <user>@<host>
copy
Run a command only when load average is below a certain threshold
$ echo "rm -rf /unwanted-but-large/folder" | batch
copy
Create a quick back-up copy of a file
$ cp file.txt{,.bak}
copy
Start COMMAND, and kill it if still running after 5 seconds
$ timeout 5s COMMAND
copy
Attach screen over ssh
$ ssh -t remote_host screen -r
copy
Show a 4-way scrollable process tree with full details.
$ ps awwfux | less -S
copy
List all bash shortcuts
$ bind -P
copy
RTFM function
$ rtfm() { help $@ || man $@ || $BROWSER "http://www.google.com/search?q=$@"; }
copy
Eavesdrop on your system
$ diff <( lsof -p 1234) <(sleep 10; lsof -p 1234)
copy
Remove all files previously extracted from a tar(.gz) file.
$ tar -tf <file. tar.gz> | xargs rm -r
copy
Broadcast your shell thru ports 5000, 5001, 5002 ...
$ script -qf | tee >(nc -kl 5000) >(nc -kl 5001) >(nc -kl 5002)
copy
directly ssh to host B that is only accessible through host A
$ ssh -t hostA ssh hostB
copy
which program is this port belongs to ?
$ lsof -i tcp:80
copy
What is my public IP-address?
$ curl ifconfig.me
copy
Retry the previous command until it exits successfully
$ until !!; do :; done
copy
Synchronize date and time with a server over ssh
$ date --set="$(ssh user@server date)"
copy
Edit a google doc with vim
$ google docs edit --title "To-Do List" -- editor vim
copy
Run a file system check on your next boot.
$ sudo touch /forcefsck
copy
List only the directories
$ ls -d */
copy
Share a terminal screen with others
$ % screen -r someuser/
copy
Google text-to-speech in mp3 format
$ wget -q -U Mozilla -O output.mp3 "http://translate.google.com/translate_tts?ie=UTF-8&tl=en&q=hello+world
copy
Download all images from a site
$ wget -r -l1 --no-parent -nH -nd -P/tmp -A".gif,.jpg" http://example.com/images
copy
Download Youtube video with wget!
$ wget http://www.youtube.com/watch?v=dQw4w9WgXcQ -qO- | sed -n "/fmt_url_map/{s/[\'\"\|]/
/g;p}" | sed -n '/^fmt_url_map/,/videoplayback/p' | sed -e :a -e '$q;N;5,$D;ba' | tr -d '
' | sed -e 's/\(.*\),\(.\)\{1,3\}/\1/' | wget -i - -O surprise.flv
copy
Python version 3: Serve current directory tree at http://$HOSTNAME:8000/
$ python -m http.server
copy
Get your outgoing IP address
$ dig +short myip.opendns.com @resolver1.opendns.com
copy
Binary Clock
$ watch -n 1 'echo "obase=2;`date +%s`" | bc'
copy
Sort the size usage of a directory tree by gigabytes, kilobytes, megabytes, then bytes.
$ du -b --max-depth 1 | sort -nr | perl -pe 's{([0-9]+)}{sprintf "%.1f%s", $1>=2**30? ($1/2**30, "G"): $1>=2**20? ($1/2**20, "M"): $1>=2**10? ($1/2**10, "K"): ($1, "")}e'
copy
Duplicate installed packages from one machine to the other (RPM-based systems)
$ ssh root@remote.host "rpm -qa" | xargs yum -y install
copy
Draw kernel module dependancy graph.
$ lsmod | perl -e ' print "digraph \" lsmod\" {";<>;while(<>){@_=split/\s+/; print "\"$_[0]\" -> \"$_\"
" for split/,/,$_[3]} print "}"' | dot -Tpng | display -
copy
Compare two directory trees.
$ diff <(cd dir1 && find | sort) <(cd dir2 && find | sort)
copy
Bring the word under the cursor on the :ex line in Vim
$ :<C-R><C-W>
copy
Remind yourself to leave in 15 minutes
$ leave +15
copy
make directory tree
$ mkdir -p work/{d1,d2}/{src,bin,bak}
copy
Convert Youtube videos to MP3
$ youtube-dl -t --extract-audio --audio-format mp3 YOUTUBE_URL_HERE
copy
Find out how much data is waiting to be written to disk
$ grep ^Dirty /proc/meminfo
copy
Use tee to process a pipe with two or more processes
$ echo "tee can split a pipe in two"|tee >(rev) >(tr ' ' '_')
copy
Show apps that use internet connection at the moment.
$ lsof -P -i -n | cut -f 1 -d " "| uniq | tail -n +2
copy
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
copy
Port Knocking!
$ knock <host> 3000 4000 5000 && ssh -p <port> user@host && knock <host> 5000 4000 3000
copy
Add timestamp to history
$ export HISTTIMEFORMAT="%F %T "
copy
Recursively change permissions on files, leave directories alone.
$ find ./ -type f -exec chmod 644 {} \;
copy
Find files that have been modified on your system in the past 60 minutes
$ sudo find / -mmin 60 -type f
copy
Quick access to ASCII code of a key
$ showkey -a
copy
using `!#$' to referance backward-word
$ cp /work/host/phone/ui/main. cpp !#$:s/host/target
copy
Search recursively to find a word or phrase in certain file types, such as C code
$ find . -name "*.[ch]" -exec grep -i -H "search pharse" {} \;
copy
Intercept, monitor and manipulate a TCP connection.
$ mkfifo /tmp/fifo; cat /tmp/fifo | nc -l -p 1234 | tee -a to.log | nc machine port | tee -a from.log > /tmp/fifo
copy
Block known dirty hosts from reaching your machine
$ wget -qO - http://infiltrated.net/blacklisted|awk '!/#|[a-z]/&&/./{print "iptables -A INPUT -s "$1" -j DROP"}'
copy
check site ssl certificate dates
$ echo | openssl s_client -connect www.google.com:443 2>/dev/null | openssl x509 -dates -noout
copy
find files in a date range
$ find . -type f -newermt "2010-01-01" ! -newermt "2010-06-01"
copy
Control ssh connection
$ [enter]~?
copy
run complex remote shell cmds over ssh, without escaping quotes
$ ssh host -l user $(<cmd.txt)
copy
Create a directory and change into it at the same time
$ md () { mkdir -p "$@" && cd "$@"; }
copy
Colorized grep in less
$ grep --color=always | less -R
copy
Exclude multiple columns using AWK
$ awk '{$1=$3=""}1' file
copy
ls not pattern
$ ls !(*.gz)
copy
output your microphone to a remote computer's speaker
$ arecord -f dat | ssh -C user@host aplay -f dat
copy
analyze traffic remotely over ssh w/ wireshark
$ ssh root@server.com 'tshark -f "port !22" -w -' | wireshark -k -i -
copy
Given a file path, unplug the USB device on which the file is located (the file must be on an USB device !)
$ echo $( sudo lshw -businfo | grep -B 1 -m 1 $(df "/path/to/file" | tail -1 | awk '{print $1}' | cut -c 6-8) | head -n 1 | awk '{print $1}' | cut -c 5- | tr ":" "-") | sudo tee /sys/bus/usb/drivers/usb/unbind
copy
Remove a line in a text file. Useful to fix "ssh host key change" warnings
$ sed -i 8d ~/.ssh/known_hosts
copy
Save a file you edited in vim without the needed permissions (no echo)
$ :w !sudo tee > /dev/null %
copy
Remove blank lines from a file using grep and save output to new file
$ grep . filename > newfilename
copy
delete a line from your shell history
$ history -d
copy
Get the IP of the host your coming from when logged in remotely
$ echo ${SSH_CLIENT%% *}
copy
Random Number Between 1 And X
$ echo $[RANDOM%X+1]
copy
Lists all listening ports together with the PID of the associated process
$ lsof -Pan -i tcp -i udp
copy
easily find megabyte eating files or directories
$ alias dush="du -sm *|sort -n|tail"
copy
Exclude .svn, .git and other VCS junk for a pristine tarball
$ tar --exclude-vcs -cf src. tar src/
copy
exit without saving history
$ kill -9 $$
copy
How to establish a remote Gnu screen session that you can re-connect to
$ ssh -t user@some.domain.com /usr/bin/screen -xRR
copy
Copy a MySQL Database to a new Server via SSH with one command
$ mysqldump --add-drop-table --extended-insert --force --log-error=error.log -uUSER -pPASS OLD_DB_NAME | ssh -C user@newhost "mysql -uUSER -pPASS NEW_DB_NAME"
copy
Convert PDF to JPG
$ for file in `ls *.pdf`; do convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 $ file `echo $ file | sed 's/\.pdf$/\.jpg/'`; done
copy
Find usb device
$ diff <(lsusb) <(sleep 3s && lsusb)
copy
find all file larger than 500M
$ find / -type f -size +500M
copy
notify yourself when a long-running command which has ALREADY STARTED is finished
$ <ctrl+z> fg; notify_me
copy
Create colorized html file from Vim or Vimdiff
$ :TOhtml
copy
live ssh network throughput test
$ yes | pv | ssh $host "cat > /dev/null"
copy
Create a nifty overview of the hardware in your computer
$ lshw -html > hardware.html
copy
Save your sessions in vim to resume later
$ :mksession! <filename>
copy
Tell local Debian machine to install packages used by remote Debian machine
$ ssh remotehost ' dpkg --get-selections' | dpkg --set-selections && dselect install
copy
Bind a key with a command
$ bind -x '"\C-l":ls -l'
copy
Take screenshot through SSH
$ DISPLAY=:0.0 import -window root /tmp/shot.png
copy
intersection between two files
$ grep -Fx -f file1 file2
copy
GREP a PDF file.
$ pdftotext [file] - | grep 'YourPattern'
copy
Colorful man
$ apt-get install most && update-alternatives --set pager /usr/bin/ most
copy
copy working directory and compress it on-the-fly while showing progress
$ tar -cf - . | pv -s $(du -sb . | awk '{print $1}') | gzip > out.tgz
copy
prints line numbers
$ nl
copy
convert unixtime to human-readable
$ date -d @1234567890
copy
A fun thing to do with ram is actually open it up and take a peek. This command will show you all the string (plain text) values in ram
$ sudo strings /dev/mem
copy
Diff on two variables
$ diff <(echo "$a") <(echo "$b")
copy
Prettify an XML file
$ tidy -xml -i -m [file]
copy
Encrypted archive with openssl and tar
$ tar --create --file - --posix --gzip -- <dir> | openssl enc -e -aes256 -out <file>
copy
Convert seconds into minutes and seconds
$ bc <<< 'obase=60;299'
copy
Alias HEAD for automatic smart output
$ alias head='head -n $((${LINES:-`tput lines 2>/dev/null||echo -n 12`} - 2))'
copy
Pipe stdout and stderr, etc., to separate commands
$ some_command > >(/bin/cmd_for_stdout) 2> >(/bin/cmd_for_stderr)
copy
Manually Pause/Unpause Firefox Process with POSIX-Signals
$ killall -STOP -m firefox
copy
Gets a random Futurama quote from /.
$ curl -Is slashdot.org | egrep '^X-(F|B|L)' | cut -d \- -f 2
copy
Use lynx to run repeating website actions
$ lynx -accept_all_cookies -cmd_script=/your/keystroke-file
copy
runs a bash script in debugging mode
$ bash -x ./post_to_commandlinefu.sh
copy
Instead of writing a multiline if/then/else/fi construct you can do that by one line
$ [[ test_condition ]] && if_true_do_this || otherwise_do_that
copy
Display a list of committers sorted by the frequency of commits
$ svn log -q|grep "|"|awk "{print \$3}"|sort|uniq -c|sort -nr
copy
check the status of 'dd' in progress (OS X)
$ CTRL + T
copy
A child process which survives the parent's death (for sure)
$ ( command & )
copy
prevent accidents while using wildcards
$ rm *.txt <TAB> <TAB>
copy
Opens vi/vim at pattern in file
$ vi +/pattern [file]
copy
April Fools' Day Prank
$ PROMPT_COMMAND='if [ $RANDOM -le 3200 ]; then printf "\0337\033[%d;%dH\033[4%dm \033[m\0338" $((RANDOM%LINES+1)) $((RANDOM%COLUMNS+1)) $((RANDOM%8)); fi'
copy
Press Any Key to Continue
$ read -sn 1 -p "Press any key to continue..."
copy
Get your external IP address
$ curl ip.appspot.com
copy
List installed deb packages by size
$ dpkg-query -Wf '${Installed-Size}\t${Package}
' | sort -n
copy
backup all your commandlinefu.com favourites to a plaintext file
$ clfavs(){ URL="http://www.commandlinefu.com"; wget -O - --save-cookies c --post-data "username=$1&password=$2&submit=Let+me+in" $URL/users/signin;for i in `seq 0 25 $3`;do wget -O - --load-cookies c $URL/commands/favourites/plaintext/$i >>$4;done;rm -f c;}
copy
send echo to socket network
$ echo "foo" > /dev/tcp/192.168.1.2/25
copy
Schedule a script or command in x num hours, silently run in the background even if logged out
$ ( ( sleep 2h; your-command your-args ) & )
copy
Go to parent directory of filename edited in last command
$ cd !$:h
copy
Draw a Sierpinski triangle
$ perl -e 'print "P1
256 256
", map {$_&($_>>8)?1:0} (0..0xffff)' | display
copy
Run a long job and notify me when it's finished
$ ./my-really-long-job.sh && notify-send "Job finished"
copy
Make anything more awesome
$ command | figlet
copy
List all files opened by a particular command
$ lsof -c dhcpd
copy
Nicely display permissions in octal format with filename
$ stat -c '%A %a %n' *
copy
recursive search and replace old with new string, inside files
$ $ grep -rl oldstring . |xargs sed -i -e 's/oldstring/newstring/'
copy
shut of the screen.
$ xset dpms force standby
copy
Create a single-use TCP (or UDP) proxy
$ nc -l -p 2000 -c " nc example.org 3000"
copy
read manpage of a unix command as pdf in preview (Os X)
$ man -t UNIX_COMMAND | open -f -a preview
copy
Switch 2 characters on a command line.
$ ctrl-t
copy
List the number and type of active network connections
$ netstat -ant | awk '{print $NF}' | grep -v '[a-z]' | sort | uniq -c
copy
Use file(1) to view device information
$ file -s /dev/sd*
copy
exclude a column with cut
$ cut -f5 --complement
copy
Recover a deleted file
$ grep -a -B 25 -A 100 'some string in the file' /dev/sda1 > results.txt
copy
Insert the last argument of the previous command
$ <ESC> .
copy
View the newest xkcd comic.
$ xkcd(){ wget -qO- http://xkcd.com/|tee >(feh $(grep -Po '(?<=")http://imgs[^/]+/comics/[^"]+\.\w{3}'))|grep -Po '(?<=(\w{3})" title=").*(?=" alt)';}
copy
Create an audio test CD of sine waves from 1 to 99 Hz
$ ( echo CD_DA; for f in {01..99}; do echo "$f Hz">&2; sox -nt cdda -r44100 -c2 $f.cdda synth 30 sine $f; echo TRACK AUDIO; echo FILE \"$f.cdda\" 0; done) > cdrdao.toc && cdrdao write cdrdao.toc && rm ??.cdda cdrdao.toc
copy
Remove color codes (special characters) with sed
$ sed -r "s/\x1B\[([0-9]{1,2}(;[0-9]{1,2})?)?[m|K]//g"
copy
throttle bandwidth with cstream
$ tar -cj /backup | cstream -t 777k | ssh host ' tar -xj -C /backup'
copy
When feeling down, this command helps
$ sl
copy
Brute force discover
$ sudo zcat /var/log/auth.log.*.gz | awk '/Failed password/&&!/ for invalid user/{a[$9]++}/Failed password for invalid user/{a["*" $11]++}END{ for (i in a) printf "%6s\t%s
", a[i], i|"sort -n"}'
copy
find geographical location of an ip address
$ lynx -dump http://www.ip-adress.com/ip_tracer/?QRY=$1|grep address|egrep 'city|state|country'|awk '{print $3,$4,$5,$6,$7,$8}'|sed 's\ip address flag \\'|sed 's\My\\'
copy
Speed up launch of firefox
$ find ~ -name '*.sqlite' -exec sqlite3 '{}' 'VACUUM;' \;
copy
Create strong, but easy to remember password
$ read -s pass; echo $pass | md5sum | base64 | cut -c -16
copy
format txt as table not joining empty columns
$ column -tns: /etc/passwd
copy
Find Duplicate Files (based on size first, then MD5 hash)
$ fdupes -r .
copy
Shell recorder with replay
$ script -t /tmp/mylog.out 2>/tmp/mylog.time; <do your work>; <CTRL-D>; scriptreplay /tmp/mylog.time /tmp/mylog.out
copy
Bind a key with a command
$ bind '"\C-l":"ls -l
"'
copy
List files with quotes around each filename
$ ls -Q
copy
Makes you look busy
$ alias busy='my_file=$(find /usr/include -type f | sort -R | head -n 1); my_len=$(wc -l $my_file | awk "{print $1}"); let "r = $RANDOM % $my_len" 2>/dev/null; vim +$r $my_file'
copy
Duplicate several drives concurrently
$ dd if=/dev/sda | tee >( dd of=/dev/sdb) | dd of=/dev/sdc
copy
Listen to BBC Radio from the command line.
$ bbcradio() { local s PS3="Select a station: "; select s in 1 1x 2 3 4 5 6 7 "A sian Network an" "Nation s & Local lcl";do break;done; s=($ s);mplayer -playli st "http://www.bbc.co.uk/radio/li sten/live/r"${ s[@]: -1}".a sx";}
copy
Monitor bandwidth by pid
$ nethogs -p eth0
copy
Execute a command with a timeout
$ timeout 10 sleep 11
copy
use vim to get colorful diff output
$ svn diff | view -
copy
find files containing text
$ grep -lir "some text" *
copy
Quickly graph a list of numbers
$ gnuplot -persist <(echo "plot '<(sort -n listOfNumbers.txt)' with lines")
copy
Perform a branching conditional
$ true && { echo success;} || { echo failed; }
copy
Resume scp of a big file
$ rsync --partial --progress --rsh=ssh $file_source $user@$host:$destination_file
copy
Use tee + process substitution to split STDOUT to multiple commands
$ some_command | tee >(command1) >(command2) >(command3) ... | command4
copy
Analyse an Apache access log for the most common IP addresses
$ tail -10000 access_log | awk '{print $1}' | sort | uniq -c | sort -n | tail
copy
Annotate tail -f with timestamps
$ tail -f file | while read; do echo "$(date +%T.%N) $REPLY"; done
copy
Fast, built-in pipe-based data sink
$ <COMMAND> |:
copy
Generate an XKCD #936 style 4 word password
$ shuf -n4 /usr/share/dict/words | tr -d '
'
copy
Repoint an existing symlink to a new location
$ ln -nsf <TARGET> <LINK>
copy
GRUB2: set Super Mario as startup tune
$ echo "GRUB_INIT_TUNE=\"1000 334 1 334 1 0 1 334 1 0 1 261 1 334 1 0 1 392 2 0 4 196 2\"" | sudo tee -a /etc/default/grub > /dev/null && sudo update-grub
copy
Diff remote webpages using wget
$ diff <(wget -q -O - URL1) <(wget -q -O - URL2)
copy
Close a hanging ssh session
$ ~.
copy
processes per user counter
$ ps hax -o user | sort | uniq -c
copy
convert filenames in current directory to lowercase
$ rename 'y/A-Z/a-z/' *
copy
Find files that were modified by a given command
$ touch /tmp/file ; $EXECUTECOMMAND ; find /path -newer /tmp/file
copy
Terminal - Show directories in the PATH, one per line with sed and bash3.X `here string'
$ tr : '
' <<<$PATH
copy
Cut out a piece of film from a file. Choose an arbitrary length and starting time.
$ ffmpeg -vcodec copy -acodec copy -i orginalfile -ss 00:01:30 -t 0:0:20 newfile
copy
List of commands you use most often
$ history | awk '{print $2}' | sort | uniq -c | sort -rn | head
copy
Efficiently print a line deep in a huge log file
$ sed '1000000!d;q' < massive-log-file.log
copy
prevent large files from being cached in memory (backups!)
$ nocache <I/O-heavy-command>
copy
Check if system is 32bit or 64bit
$ getconf LONG_BIT
copy
dmesg with colored human-readable dates
$ dmesg -T|sed -e 's|\(^.*'`date +%Y`']\)\(.*\)|\x1b[0;34m\1\x1b[0m - \2|g'
copy
convert single digit to double digits
$ for i in ?.ogg; do mv $i 0$i; done
copy
Limit the cpu usage of a process
$ sudo cpulimit -p pid -l 50
copy
Rapidly invoke an editor to write a long, complex, or tricky command
$ <ESC> v or ctrl-x ctrl-e
copy
Single use vnc-over-ssh connection
$ ssh -f -L 5900:localhost:5900 your. ssh.server "x11vnc -safer -localhost -nopw -once -display :0"; vinagre localhost:5900
copy
List alive hosts in specific subnet
$ nmap -sP 192.168.1.0/24
copy
View all date formats, Quick Reference Help Alias
$ alias dateh=' date --help|sed -n "/^ *%%/,/^ *%Z/p"|while read l;do F=${l/% */}; date +%$F:"|'"'"'${F//%n/ }'"'"'|${l#* }";done|sed "s/\ *|\ */|/g" |column -s "|" -t'
copy
your terminal sings
$ echo {1..199}" bottles of beer on the wall, cold bottle of beer, take one down, pass it around, one less bottle of beer on the wall,, " | espeak -v english -s 140
copy
Make sure a script is run in a terminal.
$ [ -t 0 ] || exit 1
copy
Matrix Style
$ echo -e "\e[32m"; while :; do for i in {1..16}; do r="$(($RANDOM % 2))"; if [[ $(($RANDOM % 5)) == 1 ]]; then if [[ $(($RANDOM % 4)) == 1 ]]; then v+="\e[1m $r "; else v+="\e[2m $r "; fi; else v+=" "; fi; done; echo -e "$v"; v=""; done
copy
Quickly (soft-)reboot skipping hardware checks
$ /sbin/kexec -l /boot/$KERNEL --append="$KERNELPARAMTERS" --initrd=/boot/$INITRD; sync; /sbin/kexec -e
copy
pipe output of a command to your clipboard
$ some command|xsel --clipboard
copy
Recursively compare two directories and output their differences on a readable format
$ diff -urp /originaldirectory /modifieddirectory
copy
Find broken symlinks and delete them
$ find -L /path/to/check -type l -delete
copy
ls -hog --> a more compact ls -l
$ ls -hog
copy
git remove files which have been deleted
$ git rm $( git ls-files --deleted)
copy
Silently ensures that a FS is mounted on the given mount point (checks if it's OK, otherwise unmount, create dir and mount)
$ ( mountpoint -q "/media/mpdr1" && df /media/mpdr1/* > /dev/null 2>&1) || (( sudo u mount "/media/mpdr1" > /dev/null 2>&1 || true) && ( sudo mkdir "/media/mpdr1" > /dev/null 2>&1 || true) && sudo mount "/dev/sdd1" "/media/mpdr1")
copy
sniff network traffic on a given interface and displays the IP addresses of the machines communicating with the current host (one IP per line)
$ sudo tcpdump -i wlan0 -n ip | awk '{ print gensub(/(.*)\..*/,"\\1","g",$3), $4, gensub(/(.*)\..*/,"\\1","g",$5) }' | awk -F " > " '{ print $1"
"$2}'
copy
Create a local compressed tarball from remote host directory
$ ssh user@host "tar -zcf - /path/to/dir" > dir.tar.gz
copy
df without line wrap on long FS name
$ df -P | column -t
copy
send a circular
$ wall <<< "Broadcast This"
copy
The BOFH Excuse Server
$ telnet towel.blinkenlights.nl 666
copy
dd with progress bar and statistics
$ sudo dd if=/dev/sdc bs=4096 | pv -s 2G | sudo dd bs=4096 of=~/USB_BLACK_BACKUP.IMG
copy
I finally found out how to use notify-send with at or cron
$ echo " export DISPLAY=:0; export XAUTHORITY=~/.Xauthority; notify-send test" | at now+1minute
copy
See udev at work
$ udevadm monitor
copy
Backup all MySQL Databases to individual files
$ for db in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $db | gzip > "/backups/ mysqldump-$(hostname)-$db-$(date +%Y-%m-%d-%H.%M.%S).gz"; done
copy
Ultimate current directory usage command
$ ncdu
copy
bash: hotkey to put current commandline to text-editor
$ bash-hotkey: <CTRL+x+e>
copy
Show current working directory of a process
$ pwdx pid
copy
Have an ssh session open forever
$ autossh -M50000 -t server.example.com 'screen -raAd mysession'
copy
Base conversions with bc
$ echo "obase=2; 27" | bc -l
copy
Put readline into vi mode
$ set -o vi
copy
Transfer SSH public key to another machine in one step
$ ssh-keygen; ssh-copy-id user@host; ssh user@host
copy
Start a command on only one CPU core
$ taskset -c 0 your_command
copy
convert uppercase files to lowercase files
$ rename 'y/A-Z/a-z/' *
copy
return external ip
$ curl ipinfo.io
copy
Simple multi-user encrypted chat server for 5 users
$ ncat -vlm 5 --ssl --chat 9876
copy
Check if your ISP is intercepting DNS queries
$ dig +short which.opendns.com txt @208.67.220.220
copy
Display current time in requested time zones.
$ zdump Japan America/New_York
copy
Remove a range of lines from a file
$ sed -i <file> -re '<start>,<end>d'
copy
Stamp a text line on top of the pdf pages.
$ echo "This text gets stamped on the top of the pdf pages." | enscript -B -f Courier-Bold16 -o- | ps2pdf - | pdftk input.pdf stamp - output output.pdf
copy
Print diagram of user/groups
$ awk 'BEGIN{FS=":"; print "digraph{"}{split($4, a, ","); for (i in a) printf "\"%s\" [shape=box]
\"%s\" -> \"%s\"
", $1, a[i], $1}END{ print "}"}' /etc/group|display
copy
Create a file server, listening in port 7000
$ while true; do nc -l 7000 | tar -xvf -; done
copy
bypass any aliases and functions for the command
$ \foo
copy
Share your terminal session real-time
$ mkfifo foo; script -f foo
copy
stderr in color
$ mycommand 2> >(while read line; do echo -e "\e[01;31m$line\e[0m"; done)
copy
VI config to save files with +x when a shebang is found on line 1
$ au BufWritePost * if getline(1) =~ "^#!" | if getline(1) =~ "/bin/" | silent !chmod +x <afile> | end if | end if
copy
Create a single PDF from multiple images with ImageMagick
$ convert *.jpg output.pdf
copy
Delete all empty lines from a file with vim
$ :g/^$/d
copy
perl one-liner to get the current week number
$ date +%V
copy
DELETE all those duplicate files but one based on md5 hash comparision in the current directory tree
$ find . -type f -print0|xargs -0 md5sum|sort|perl -ne 'chomp;$ph=$h;($h,$f)=split(/\s+/,$_,2);print "$f"."\x00" if ($h eq $ph)'|xargs -0 rm -v --
copy
List recorded formular fields of Firefox
$ cd ~/.mozilla/firefox/ && sqlite3 `cat profiles.ini | grep Path | awk -F= '{print $2}'`/formhistory.sqlite "select * from moz_formhistory" && cd - > /dev/null
copy
Using awk to sum/count a column of numbers.
$ cat count.txt | awk '{ sum+=$1} END {print sum}'
copy
Get all the keyboard shortcuts in screen
$ ^A ?