Difference between revisions of "Miscellaneous commands"
(→Other) |
(→Command-line calculator) |
||
(37 intermediate revisions by the same user not shown) | |||
Line 13: | Line 13: | ||
rphonebook: John Doe Portland OR | rphonebook: John Doe Portland OR | ||
bphonebook: Blue Sushi Seattle WA | bphonebook: Blue Sushi Seattle WA | ||
+ | |||
+ | *Find YouTube videos with your "word" in the video ID: | ||
+ | allinurl:[your word here] site:youtube.com/watch | ||
Note: See [http://www.googletutor.com/google-manual/ Google Search Manual] and [http://projects.felipc.com/gcl/ Google command line help] for more tricks. | Note: See [http://www.googletutor.com/google-manual/ Google Search Manual] and [http://projects.felipc.com/gcl/ Google command line help] for more tricks. | ||
− | ==Bulk image resize== | + | ==ImageMagick tips & tricks== |
+ | ===Bulk image resize=== | ||
If you are like me and have a high resolution digital camera, it is often necessary to resize the images before emailing them to friends and family. It is, of course, possible to manually resize them using [[Adobe Photoshop]], [[Gimp|The Gimp]], or any other image editing program. However, it is possible to automate this task using simple command line tools. | If you are like me and have a high resolution digital camera, it is often necessary to resize the images before emailing them to friends and family. It is, of course, possible to manually resize them using [[Adobe Photoshop]], [[Gimp|The Gimp]], or any other image editing program. However, it is possible to automate this task using simple command line tools. | ||
Line 26: | Line 30: | ||
Note that the program <tt>convert</tt> is part of the [[ImageMagick]] suite and you will need to have it installed to use the above commands (it is, by default, in SuSE Linux and most distributions). | Note that the program <tt>convert</tt> is part of the [[ImageMagick]] suite and you will need to have it installed to use the above commands (it is, by default, in SuSE Linux and most distributions). | ||
+ | |||
+ | ===Misc=== | ||
+ | *Show photo filenames where no physical flash device was used: | ||
+ | identify -format "%f F:%[EXIF:Flash]\n" *.jpg | egrep " F:(0|16|24|32)$" | ||
==Tracking down large files== | ==Tracking down large files== | ||
Line 40: | Line 48: | ||
==ps2png== | ==ps2png== | ||
*Convert [[PostScript]] (*.ps) files to PNG: | *Convert [[PostScript]] (*.ps) files to PNG: | ||
− | gs -sDEVICE=ppmraw -sOutputFile=- -sNOPAUSE -q foo.ps -c showpage -c quit |\ | + | $ gs -sDEVICE=ppmraw -sOutputFile=- -sNOPAUSE -q foo.ps -c showpage -c quit |\ |
− | + | pnmcrop | pnmmargin -white 10 | pnmtopng >foo.png | |
==nrg2iso== | ==nrg2iso== | ||
Line 50: | Line 58: | ||
==Selecting random lines from a file== | ==Selecting random lines from a file== | ||
− | This example could be used for printing random quotes from a file | + | This example could be used for printing random quotes from a file: |
− | <pre>FILE="/some/file_name"; | + | <pre>FILE="/some/file_name"; nlines=$(wc -l < "$FILE"); \ |
− | nlines=$(wc -l < "$FILE"); | + | IFS=$'\n'; array=($(<"$FILE")); echo "${array[$((RANDOM%nlines))]}"</pre> |
− | IFS=$'\n'; | + | |
− | array=($(<"$FILE")); | + | |
− | echo "${array[$((RANDOM%nlines))]}"</pre> | + | |
Here, <tt>nlines</tt> holds the total number of lines in the file. The file is read into an array (note the use of <tt>IFS</tt> — this splits the lines based on '<tt>\n</tt>'). Then, once the array has been populated, print a random line from it. | Here, <tt>nlines</tt> holds the total number of lines in the file. The file is read into an array (note the use of <tt>IFS</tt> — this splits the lines based on '<tt>\n</tt>'). Then, once the array has been populated, print a random line from it. | ||
Line 81: | Line 86: | ||
''Note: See [[awk]] for details.'' | ''Note: See [[awk]] for details.'' | ||
+ | |||
+ | *The following commands will print (to an actual printer) a file, starting at page 4, with a header of "ERRORS", with a line length of 80 characters, and print the whole thing 3 times: | ||
+ | pr +4 -h"ERRORS" -l80 logfile | lpr -# 3 | ||
==Linux I/O redirection== | ==Linux I/O redirection== | ||
Line 102: | Line 110: | ||
==Count number of n-word lengths== | ==Count number of n-word lengths== | ||
for i in `seq 1 32` { | for i in `seq 1 32` { | ||
− | + | grep -E '^.{'$i'}$' /usr/share/dict/words | wc -l | |
} | } | ||
# OR (depending on your shell), | # OR (depending on your shell), | ||
− | for i in `seq 1 32`; do | + | for i in `seq 1 32`; do grep -E '^.{'$i'}$' /usr/share/dict/words | wc -l; done |
Then paste the numbers together (or, just add them to the above for-loop): | Then paste the numbers together (or, just add them to the above for-loop): | ||
− | seq 1 32 | paste - tmp_n-word_lenghts.dat >n-word_lengths.dat | + | seq 1 32 | paste - tmp_n-word_lenghts.dat > n-word_lengths.dat |
==Random number generation== | ==Random number generation== | ||
− | The | + | The CLI variable <code>RANDOM</code> returns a random number between a range of 0 to 32767. The following will generate three random numbers from within this range: |
− | r=0;while [ $r -lt 3 ];do echo $RANDOM;let r=$r+1;done | + | $ r=0;while [ $r -lt 3 ];do echo $RANDOM;let r=$r+1;done |
You can create your own versions of <code>/dev/random</code> and <code>/dev/urandom</code> with the following commands: | You can create your own versions of <code>/dev/random</code> and <code>/dev/urandom</code> with the following commands: | ||
− | mknod /tmp/random c 1 8 && | + | $ mknod /tmp/random c 1 8 && |
− | mknod /tmp/urandom c 1 9 && | + | $ mknod /tmp/urandom c 1 9 && |
Or, you can use the <code>RANDOM</code> variable, like so: | Or, you can use the <code>RANDOM</code> variable, like so: | ||
− | r=0;while [ $r -lt 92160 ];do echo $RANDOM >>/tmp/urandom;let r=$r+1;done | + | $ r=0;while [ $r -lt 92160 ];do echo $RANDOM >>/tmp/urandom;let r=$r+1;done |
You can also copy the original <code>/dev/urandom</code> like so (Note: Be careful with this command!): | You can also copy the original <code>/dev/urandom</code> like so (Note: Be careful with this command!): | ||
− | dd if=/dev/urandom of=/tmp/urandom count=1 >/dev/null 2>&1 | + | $ dd if=/dev/urandom of=/tmp/urandom count=1 >/dev/null 2>&1 |
+ | |||
+ | You can also use <code>openssl</code> to generate a random key | ||
+ | $ openssl rand -base64 512 | tr -d '\r\n' > /tmp/my_random_key | ||
+ | |||
+ | Other methods include: | ||
+ | $ bash -c 'echo $RANDOM' | ||
+ | $ perl -e 'print int(rand(65535))' | ||
+ | |||
+ | * Generate a random 8-character password | ||
+ | $ dd if=/dev/urandom count=1 2> /dev/null | uuencode -m - | sed -ne 2p | cut -c-8 | ||
+ | * Or, generate 10 random 8-character passwords: | ||
+ | $ for ((n=0;n<10;n++)); do dd if=/dev/urandom count=1 2> /dev/null | uuencode -m -| sed -ne 2p | cut -c-8; done | ||
+ | Or, you could just use the <code>`pwgen`</code> utility, if you are lazy. | ||
==Command-line calculator== | ==Command-line calculator== | ||
− | |||
− | |||
− | |||
− | |||
− | + | : See: [[bc]] for details | |
− | + | ||
+ | $ echo "111111111 * 111111111" | bc # => 12345678987654321 | ||
+ | $ echo "sqrt(25)" | bc -qi # => 5 | ||
+ | $ let x=3*4-6; echo $x # => 6 | ||
+ | $ echo $[ (10 + 5) / 2] # => 7 | ||
+ | $ echo "(10+5)/2" | bc -l # => 7.50000000000000000000 | ||
+ | |||
+ | * Convert 10MB to KB from within bash by running the following: | ||
+ | $ expr $((size_in_MB << 10)) | ||
+ | $ # E.g., | ||
+ | $ expr $((10MB << 10)) # => 10240 | ||
==Split large files into small pieces== | ==Split large files into small pieces== | ||
− | + | $ ls -lh mylargefile | |
-rw-r--r-- 1 foo users 800M Feb 18 11:17 mylargefile | -rw-r--r-- 1 foo users 800M Feb 18 11:17 mylargefile | ||
− | + | $ split -b 2m largefile mylargefile_ | |
− | + | $ ls -lh mylargefile_* | head 3 | |
-rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_aa | -rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_aa | ||
-rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_ab | -rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_ab | ||
Line 143: | Line 170: | ||
==Stego trick using built-in Linux utilities== | ==Stego trick using built-in Linux utilities== | ||
− | cat foo.zip >> bar.gif # "hides" 'foo.zip' inside 'bar.gif' | + | # see: https://gist.github.com/christophchamp/8e086f73c148510c0fc6 |
− | + | $ cat foo.zip >> bar.gif # "hides" 'foo.zip' inside 'bar.gif' | |
− | unzip bar.gif | + | $ qiv bar.gif # views just fine (note: you can use any image viewer you like here) |
+ | $ unzip bar.gif # extracts 'foo.zip' | ||
+ | |||
+ | ==cat tricks== | ||
− | + | * cat and squeeze-blank: | |
The [[cat]] utility has a nice little feature that allows you to "squeeze" multiple blank lines into a single line. In other words, never print more than one single blank line. | The [[cat]] utility has a nice little feature that allows you to "squeeze" multiple blank lines into a single line. In other words, never print more than one single blank line. | ||
cat -s foo | tr -d '\f' | cat -s foo | tr -d '\f' | ||
The second command, [[tr]], just says delete ("<code>-d</code>") any form feeds (you would use this if you want to print the file). | The second command, [[tr]], just says delete ("<code>-d</code>") any form feeds (you would use this if you want to print the file). | ||
+ | |||
+ | * cat the contents of file <code>foo</code>, then the STDOUT ("<code>bar</code>"), then the contents of file <code>baz</code>: | ||
+ | echo "bar" | cat foo - baz | ||
==Create a favicon== | ==Create a favicon== | ||
Line 163: | Line 196: | ||
see: [http://www.smashingmagazine.com/2007/06/14/creative-favicons-when-small-is-beautiful/ Creative Favicons: When Small Is Beautiful] for ideas | see: [http://www.smashingmagazine.com/2007/06/14/creative-favicons-when-small-is-beautiful/ Creative Favicons: When Small Is Beautiful] for ideas | ||
+ | |||
+ | ==Check if an OS is 32- or 64-bit== | ||
+ | |||
+ | $ uname -a | ||
+ | |||
+ | :If 32-bit, it will look something like: | ||
+ | Linux hostname 3.8.0-33-generic #48-Ubuntu SMP Wed Oct 23 17:26:34 UTC 2013 i686 i686 i686 GNU/Linux | ||
+ | :If 64-bit: | ||
+ | Linux hostname 3.8.0-33-generic #48-Ubuntu SMP Wed Oct 23 17:26:34 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux | ||
+ | |||
+ | * Note: The following does not work on OSes using [[systemd]]: | ||
+ | $ file /sbin/init | ||
+ | /sbin/init: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)... | ||
+ | # ~OR~ | ||
+ | /sbin/init: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV)... | ||
+ | |||
+ | $ uname -m | ||
+ | i686 # <- 32-bit | ||
+ | # ~OR~ | ||
+ | x86_64 # <- 64-bit | ||
+ | |||
+ | Note: On [[Raspberry Pi|Raspberry Pi's]]: | ||
+ | $ arch || uname -a | ||
+ | armv7l # <- 32-bit => ARMv7 Processor rev 4 (v7l) | ||
+ | armv8 # <- 64-bit => ARMv8 Processor | ||
+ | |||
+ | $ arch | ||
+ | $ getconf LONG_BIT | ||
+ | 32 | ||
+ | # ~OR~ | ||
+ | 64 | ||
+ | |||
+ | * On Debian-based distros: | ||
+ | $ dpkg --print-architecture | ||
+ | amd64 # <- 64-bit | ||
+ | |||
+ | * To see if your processor is 64-bit, you can run this command: | ||
+ | $ egrep -c ' lm ' /proc/cpuinfo | ||
+ | # ~OR~ | ||
+ | $ grep -Ec ' lm ' /proc/cpuinfo | ||
+ | |||
+ | :If <code>0</code> is printed, it means that your CPU is ''not'' 64-bit. | ||
+ | :If <code>1</code> or higher, it is. Note: <code>lm</code> stands for "Long Mode" which equates to a 64-bit CPU. If, for an example, the above command(s) return something like "12", that means your CPU supports 12 x threads (2 x ''n'' cores) of 64-bit nodes. | ||
+ | |||
+ | * Check if a remote host is running a 32- or a 64-bit [[Linux]] kernel: | ||
+ | $ ssh $REMOTE_HOST getconf LONG_BIT | ||
==Misc== | ==Misc== | ||
*Save man pages as plain text: | *Save man pages as plain text: | ||
− | man grep | col -b > grep.txt | + | $ man grep | col -b > grep.txt |
*Display the total number of files in the current working directory and all of its subdirectories: | *Display the total number of files in the current working directory and all of its subdirectories: | ||
− | find . -type f -print | wc -l | + | $ find . -type f -print | wc -l |
*Display a list of directories and how much space they consume, sorted from the largest to the smallest: | *Display a list of directories and how much space they consume, sorted from the largest to the smallest: | ||
− | du | sort -nr | + | $ du | sort -nr |
*Format text for printing: | *Format text for printing: | ||
− | cat poorly_formatted_report.txt | fmt | pr | lpr | + | $ cat poorly_formatted_report.txt | fmt | pr | lpr |
− | cat unsorted_list_with_dupes.txt | sort | uniq | pr | lpr | + | $ cat unsorted_list_with_dupes.txt | sort | uniq | pr | lpr |
*Delete files older than ''n'' days: | *Delete files older than ''n'' days: | ||
− | find /path/to/files* -mtime +5 -exec rm {} \; | + | $ find /path/to/files* -mtime +5 -exec rm {} \; |
*Download multiple files in bash using for-loop: | *Download multiple files in bash using for-loop: | ||
− | for (( a=1; a<=96; a++ )) ;do wget -c http://www. | + | $ for (( a=1; a<=96; a++ )) ;do wget -c <nowiki>http://www.example.com/images/$a.jpg</nowiki>; done |
*Multiple unzip: The following command will <tt>unzip</tt> all zip files in the current directory: | *Multiple unzip: The following command will <tt>unzip</tt> all zip files in the current directory: | ||
− | for i in $(ls *.zip); do unzip $i; done | + | $ for i in $(ls *.zip); do unzip $i; done |
*Copying files through [[tar]] filter: | *Copying files through [[tar]] filter: | ||
− | (cd /path/dir/from && tar -cvf - .) | (cd /path/dir/to && tar -xvf -) | + | $ (cd /path/dir/from && tar -cvf - .) | (cd /path/dir/to && tar -xvf -) |
*Look up the definition of a word from the CLI: | *Look up the definition of a word from the CLI: | ||
− | curl dict://dict.org/d:word | + | $ curl dict://dict.org/d:word |
*Timed read-input using [[bash]]: | *Timed read-input using [[bash]]: | ||
− | answer="yes";read -p "Do you wish to install now? " -t 10 answer;echo " Timed out; | + | $ answer="yes";read -p "Do you wish to install now? " -t 10 answer;echo " Timed out; assuming $answer"; |
*Check current battery charge system temperature: | *Check current battery charge system temperature: | ||
− | acpi -t | + | $ acpi -t |
*Display information about all system users: | *Display information about all system users: | ||
− | finger -l | + | $ finger -l |
+ | #~OR~ | ||
+ | $ pinky | ||
*Display distribution and version: | *Display distribution and version: | ||
− | cat /etc/issue | + | $ cat /etc/issue |
+ | # OR | ||
+ | $ cat /etc/release | ||
+ | *What is the longest word you can think of where no letter appears more than once? | ||
+ | $ grep -Evi '(.).*\1' /usr/share/dict/words | awk '{ print length($0),$0 }' | sort -nr | head -n 8 | ||
+ | *urlencode a given URL: | ||
+ | $ URL="foo bar";echo $(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$URL") | ||
+ | $ #~OR~ | ||
+ | $ URL=$(php -r "echo urlencode(\"foo bar\");") | ||
+ | *Create your own sub-mlocate database to search only specific paths: | ||
+ | $ updatedb -l 0 -U /usr/lib/python2.6/ -o /root/python.db | ||
+ | $ locate -d /root/python.db httplib | ||
+ | # OR: | ||
+ | $ alias pylocate='locate -d /root/python.db' | ||
+ | $ pylocate httplib | ||
+ | # OR: | ||
+ | $ updatedb -i -l 0 -U `python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"` \ | ||
+ | -o /home/bob/.mlocate/python-dist-packages.db | ||
+ | $ alias pylocate='locate -i -d /root/python.db' # case insensitive search | ||
+ | $ pylocate mysql | ||
+ | # OR: | ||
+ | $ alias hlocate='locate -d /home/home.db' | ||
+ | $ hlocate foobar | ||
+ | # OR: | ||
+ | $ locate -d /home/home.db -d /root/python.db foobar | ||
+ | *Tell mlocate to ignore certain paths by editing the <code>/etc/updatedb.conf</code> file and add the path you wish to ignore to: | ||
+ | $ PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs" | ||
+ | *Get the number of days since the root password was last changed: | ||
+ | $ echo "$(echo `date +%s`/86400|bc) - $(sudo awk -F: /^root/'{print $3}' /etc/shadow)" | bc | ||
+ | #~OR~ | ||
+ | $ echo $(($((`date +%s`/86400))-$(sudo awk -F: /^root/'{print $3}' /etc/shadow))) | ||
==See also== | ==See also== | ||
Line 228: | Line 339: | ||
===Other=== | ===Other=== | ||
*[http://www.scottklarr.com/topic/115/linux-unix-cheat-sheets---the-ultimate-collection/ Linux-Unix cheat sheets - The ultimate collection] | *[http://www.scottklarr.com/topic/115/linux-unix-cheat-sheets---the-ultimate-collection/ Linux-Unix cheat sheets - The ultimate collection] | ||
+ | *[http://cb.vu/unixtoolbox.xhtml Unix Toolbox] | ||
+ | *[http://www.shell-fu.org/ shell-fu] — collects as many little CLI commands as possible | ||
*[http://phpgroupware.org/ phpGroupWare] | *[http://phpgroupware.org/ phpGroupWare] | ||
*[http://gentoo-wiki.com/HOWTO_Auto_mount_filesystems_(AUTOFS) HOWTO Auto mount filesystems (AUTOFS)] | *[http://gentoo-wiki.com/HOWTO_Auto_mount_filesystems_(AUTOFS) HOWTO Auto mount filesystems (AUTOFS)] | ||
Line 256: | Line 369: | ||
*[http://www.xs4all.nl/~carlo17/howto/ Carlo Wood's HOWTOs] | *[http://www.xs4all.nl/~carlo17/howto/ Carlo Wood's HOWTOs] | ||
*[http://www.andrews-corner.org/mutt.html Using Mutt with Gmail] | *[http://www.andrews-corner.org/mutt.html Using Mutt with Gmail] | ||
+ | *[http://code.google.com/p/memcachedb/wiki/Performance memcachedb] — a very fast to get/set an object | ||
+ | *[http://wordaligned.org/articles/shell-script-sets He Sells Shell Scripts to Intersect Sets] | ||
+ | *[http://polishlinux.org/apps/cli/defragmentation-of-linux-filesystems/ Defragmentation of Linux Filesystems] | ||
==External links== | ==External links== |
Latest revision as of 23:38, 10 September 2021
This article will present various miscellaneous commands tested in Linux (running SuSE 10.2+ and Mandriva). Most of these will be simple command line tools. Eventually, many of these will have their own article. For now, they are presented as is with absolutely no guarantee and zero responsibility on my part if they cause loss of information or files. Use at your own risk.
Contents
- 1 Google tricks
- 2 ImageMagick tips & tricks
- 3 Tracking down large files
- 4 Finding files containing a string in a directory hierarchy
- 5 ps2png
- 6 nrg2iso
- 7 Selecting random lines from a file
- 8 Printing a block of text from a file
- 9 Linux I/O redirection
- 10 Count number of n-word lengths
- 11 Random number generation
- 12 Command-line calculator
- 13 Split large files into small pieces
- 14 Stego trick using built-in Linux utilities
- 15 cat tricks
- 16 Create a favicon
- 17 Check if an OS is 32- or 64-bit
- 18 Misc
- 19 See also
- 20 To Do
- 21 External links
Google tricks
- Finding files:
-inurl:(htm|html|php) intitle:"index of" +"last modified" +"parent directory" +description +size +(jpg|png) "Lion"
- Finding documents:
-inurl:(htm|html|php) intitle:"index of" +"last modified" +"parent directory" +description +size +(pdf|doc) "shakespeare"
- Phonebook:
rphonebook: John Doe Portland OR bphonebook: Blue Sushi Seattle WA
- Find YouTube videos with your "word" in the video ID:
allinurl:[your word here] site:youtube.com/watch
Note: See Google Search Manual and Google command line help for more tricks.
ImageMagick tips & tricks
Bulk image resize
If you are like me and have a high resolution digital camera, it is often necessary to resize the images before emailing them to friends and family. It is, of course, possible to manually resize them using Adobe Photoshop, The Gimp, or any other image editing program. However, it is possible to automate this task using simple command line tools.
For an example, say you want to resize all of the jpeg images in your current directory to 800x600 and place them in a sub-directory called, "resized". Then you would execute the following commands:
find . -maxdepth 1 -name '*.jpg' -type f -exec convert -resize 800x600 {} resized/{} \;
It is also possible to have the above commands run recursively through a directory and its sub-directories like so:
find . -follow -name '*.jpg' -type f -exec convert -resize 800x600 {} ../resized/{} \;
Note that the program convert is part of the ImageMagick suite and you will need to have it installed to use the above commands (it is, by default, in SuSE Linux and most distributions).
Misc
- Show photo filenames where no physical flash device was used:
identify -format "%f F:%[EXIF:Flash]\n" *.jpg | egrep " F:(0|16|24|32)$"
Tracking down large files
Note: See find for details. Sometimes it is necessary to find files over a certain size and it can be somewhat tedious ls-ing through your many directories. The following command will list only those files over a certain size and only within the specified directory (and sub-directories):
find some_directory/ -size +2000k -ls
which will only list files over 2000 kb (2 MB).
Finding files containing a string in a directory hierarchy
In this example, all .php files will be searched for the string "MySQL" (case-insensitive with -i) and the line numbers will also be returned (using -n):
find . -name '*.php' -type f | xargs grep -n -i 'MySQL'
ps2png
- Convert PostScript (*.ps) files to PNG:
$ gs -sDEVICE=ppmraw -sOutputFile=- -sNOPAUSE -q foo.ps -c showpage -c quit |\ pnmcrop | pnmmargin -white 10 | pnmtopng >foo.png
nrg2iso
There is a command line utility, nrg2iso, for converting to ISO files in Linux. Linux users can easily convert the NRG file using the dd command in the following way:
dd bs=1k if=myfile.nrg of=image.iso skip=300
Or, you can just mount it like so:
mount -o loop, offset=307200 /path/to/image.nrg /path/to/mount
Selecting random lines from a file
This example could be used for printing random quotes from a file:
FILE="/some/file_name"; nlines=$(wc -l < "$FILE"); \ IFS=$'\n'; array=($(<"$FILE")); echo "${array[$((RANDOM%nlines))]}"
Here, nlines holds the total number of lines in the file. The file is read into an array (note the use of IFS — this splits the lines based on '\n'). Then, once the array has been populated, print a random line from it.
Printing a block of text from a file
Say you have a file, foo, and it contains the following lines (note the capital letters and the full stop in line six):
one blah blah Two blah blah three blah blah 3, 4 Four blah blah five blah blah 5, 6 six blah blah.
- If you only want to print out lines 3, 4, and 5, execute the following command:
awk "/three/,/five/" < foo
- If you only want to print out lines starting with a capital "F", execute the following command:
awk "/^F/" < foo
- If you only want to print out lines ending in a full stop, execute the following command:
awk "/\.$/" < foo
- Finally, if you only want to print out lines containing the numbers "5" and "6", execute the following command:
awk "/[5-6]/" < foo
Note: See awk for details.
- The following commands will print (to an actual printer) a file, starting at page 4, with a header of "ERRORS", with a line length of 80 characters, and print the whole thing 3 times:
pr +4 -h"ERRORS" -l80 logfile | lpr -# 3
Linux I/O redirection
- The following command saves stdout and stderr to the files "out.txt" and "err.txt", respectively:
./cmd 1>out.txt 2>err.txt
- The following command appends stdout and stderr to the files "out.txt" and "err.txt", respectively:
./cmd 1>>out.txt 2>>err.txt
- The following command functions similar to the above two commands, but also copies stdout and stderr to the files "stdout.txt" and "stderr.txt", respectively:
(((./cmd | tee stdout.txt) 3>&1 1>&2 2>&3\ | tee stderr.txt) 3>&1 1>&2 2>&3) 1>out.txt 2>err.txt
Note: The above should be entered as one command (ie, the line that ends with a backslash is only continued on the next line because of the formatting constraints of this page).
Also note that Linux uses the following redirection codes/handles (see: redirection):
- 0 = stdin
- 1 = stdout
- 2 = stderr
Count number of n-word lengths
for i in `seq 1 32` { grep -E '^.{'$i'}$' /usr/share/dict/words | wc -l } # OR (depending on your shell), for i in `seq 1 32`; do grep -E '^.{'$i'}$' /usr/share/dict/words | wc -l; done
Then paste the numbers together (or, just add them to the above for-loop):
seq 1 32 | paste - tmp_n-word_lenghts.dat > n-word_lengths.dat
Random number generation
The CLI variable RANDOM
returns a random number between a range of 0 to 32767. The following will generate three random numbers from within this range:
$ r=0;while [ $r -lt 3 ];do echo $RANDOM;let r=$r+1;done
You can create your own versions of /dev/random
and /dev/urandom
with the following commands:
$ mknod /tmp/random c 1 8 && $ mknod /tmp/urandom c 1 9 &&
Or, you can use the RANDOM
variable, like so:
$ r=0;while [ $r -lt 92160 ];do echo $RANDOM >>/tmp/urandom;let r=$r+1;done
You can also copy the original /dev/urandom
like so (Note: Be careful with this command!):
$ dd if=/dev/urandom of=/tmp/urandom count=1 >/dev/null 2>&1
You can also use openssl
to generate a random key
$ openssl rand -base64 512 | tr -d '\r\n' > /tmp/my_random_key
Other methods include:
$ bash -c 'echo $RANDOM' $ perl -e 'print int(rand(65535))'
- Generate a random 8-character password
$ dd if=/dev/urandom count=1 2> /dev/null | uuencode -m - | sed -ne 2p | cut -c-8
- Or, generate 10 random 8-character passwords:
$ for ((n=0;n<10;n++)); do dd if=/dev/urandom count=1 2> /dev/null | uuencode -m -| sed -ne 2p | cut -c-8; done
Or, you could just use the `pwgen`
utility, if you are lazy.
Command-line calculator
- See: bc for details
$ echo "111111111 * 111111111" | bc # => 12345678987654321 $ echo "sqrt(25)" | bc -qi # => 5 $ let x=3*4-6; echo $x # => 6 $ echo $[ (10 + 5) / 2] # => 7 $ echo "(10+5)/2" | bc -l # => 7.50000000000000000000
- Convert 10MB to KB from within bash by running the following:
$ expr $((size_in_MB << 10)) $ # E.g., $ expr $((10MB << 10)) # => 10240
Split large files into small pieces
$ ls -lh mylargefile -rw-r--r-- 1 foo users 800M Feb 18 11:17 mylargefile $ split -b 2m largefile mylargefile_ $ ls -lh mylargefile_* | head 3 -rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_aa -rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_ab -rw-r--r-- 1 foo users 2.0M Feb 18 11:19 mylargefile_ac ...
Stego trick using built-in Linux utilities
# see: https://gist.github.com/christophchamp/8e086f73c148510c0fc6 $ cat foo.zip >> bar.gif # "hides" 'foo.zip' inside 'bar.gif' $ qiv bar.gif # views just fine (note: you can use any image viewer you like here) $ unzip bar.gif # extracts 'foo.zip'
cat tricks
- cat and squeeze-blank:
The cat utility has a nice little feature that allows you to "squeeze" multiple blank lines into a single line. In other words, never print more than one single blank line.
cat -s foo | tr -d '\f'
The second command, tr, just says delete ("-d
") any form feeds (you would use this if you want to print the file).
- cat the contents of file
foo
, then the STDOUT ("bar
"), then the contents of filebaz
:
echo "bar" | cat foo - baz
Create a favicon
- Step 1: Download png2ico and install (just type
make
) - Step 2: Create a PNG using something like GIMP (make sure the image is square and small; e.g. 128x128, 300x300, etc).
- Step 3: Convert the image to a 32x32 PNG (or 16x16, if you wish)
convert foo.png -resize 32x32 favicon.png
- Step 3: Convert to icon
png2ico favicon.ico favicon.png # ~ OR ~ png2ico favicon.ico logo16x16.png logo32x32.png
see: Creative Favicons: When Small Is Beautiful for ideas
Check if an OS is 32- or 64-bit
$ uname -a
- If 32-bit, it will look something like:
Linux hostname 3.8.0-33-generic #48-Ubuntu SMP Wed Oct 23 17:26:34 UTC 2013 i686 i686 i686 GNU/Linux
- If 64-bit:
Linux hostname 3.8.0-33-generic #48-Ubuntu SMP Wed Oct 23 17:26:34 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
- Note: The following does not work on OSes using systemd:
$ file /sbin/init /sbin/init: ELF 32-bit LSB shared object, Intel 80386, version 1 (SYSV)... # ~OR~ /sbin/init: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV)...
$ uname -m i686 # <- 32-bit # ~OR~ x86_64 # <- 64-bit
Note: On Raspberry Pi's:
$ arch || uname -a armv7l # <- 32-bit => ARMv7 Processor rev 4 (v7l) armv8 # <- 64-bit => ARMv8 Processor
$ arch $ getconf LONG_BIT 32 # ~OR~ 64
- On Debian-based distros:
$ dpkg --print-architecture amd64 # <- 64-bit
- To see if your processor is 64-bit, you can run this command:
$ egrep -c ' lm ' /proc/cpuinfo # ~OR~ $ grep -Ec ' lm ' /proc/cpuinfo
- If
0
is printed, it means that your CPU is not 64-bit. - If
1
or higher, it is. Note:lm
stands for "Long Mode" which equates to a 64-bit CPU. If, for an example, the above command(s) return something like "12", that means your CPU supports 12 x threads (2 x n cores) of 64-bit nodes.
- Check if a remote host is running a 32- or a 64-bit Linux kernel:
$ ssh $REMOTE_HOST getconf LONG_BIT
Misc
- Save man pages as plain text:
$ man grep | col -b > grep.txt
- Display the total number of files in the current working directory and all of its subdirectories:
$ find . -type f -print | wc -l
- Display a list of directories and how much space they consume, sorted from the largest to the smallest:
$ du | sort -nr
- Format text for printing:
$ cat poorly_formatted_report.txt | fmt | pr | lpr $ cat unsorted_list_with_dupes.txt | sort | uniq | pr | lpr
- Delete files older than n days:
$ find /path/to/files* -mtime +5 -exec rm {} \;
- Download multiple files in bash using for-loop:
$ for (( a=1; a<=96; a++ )) ;do wget -c http://www.example.com/images/$a.jpg; done
- Multiple unzip: The following command will unzip all zip files in the current directory:
$ for i in $(ls *.zip); do unzip $i; done
- Copying files through tar filter:
$ (cd /path/dir/from && tar -cvf - .) | (cd /path/dir/to && tar -xvf -)
- Look up the definition of a word from the CLI:
$ curl dict://dict.org/d:word
- Timed read-input using bash:
$ answer="yes";read -p "Do you wish to install now? " -t 10 answer;echo " Timed out; assuming $answer";
- Check current battery charge system temperature:
$ acpi -t
- Display information about all system users:
$ finger -l #~OR~ $ pinky
- Display distribution and version:
$ cat /etc/issue # OR $ cat /etc/release
- What is the longest word you can think of where no letter appears more than once?
$ grep -Evi '(.).*\1' /usr/share/dict/words | awk '{ print length($0),$0 }' | sort -nr | head -n 8
- urlencode a given URL:
$ URL="foo bar";echo $(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' "$URL") $ #~OR~ $ URL=$(php -r "echo urlencode(\"foo bar\");")
- Create your own sub-mlocate database to search only specific paths:
$ updatedb -l 0 -U /usr/lib/python2.6/ -o /root/python.db $ locate -d /root/python.db httplib # OR: $ alias pylocate='locate -d /root/python.db' $ pylocate httplib # OR: $ updatedb -i -l 0 -U `python -c "from distutils.sysconfig import get_python_lib; print get_python_lib()"` \ -o /home/bob/.mlocate/python-dist-packages.db $ alias pylocate='locate -i -d /root/python.db' # case insensitive search $ pylocate mysql # OR: $ alias hlocate='locate -d /home/home.db' $ hlocate foobar # OR: $ locate -d /home/home.db -d /root/python.db foobar
- Tell mlocate to ignore certain paths by editing the
/etc/updatedb.conf
file and add the path you wish to ignore to:
$ PRUNEPATHS="/tmp /var/spool /media /home/.ecryptfs"
- Get the number of days since the root password was last changed:
$ echo "$(echo `date +%s`/86400|bc) - $(sudo awk -F: /^root/'{print $3}' /etc/shadow)" | bc #~OR~ $ echo $(($((`date +%s`/86400))-$(sudo awk -F: /^root/'{print $3}' /etc/shadow)))
See also
To Do
Lifehacker
- Geek to Live: Back up Gmail with fetchmail
- Geek to Live: Keep your calendar in plain text with Remind
- Getting things done with rule-based list processing
- Hack Attack: Firefox and the art of keyword bookmarking
Howtoforge
- The New Hacker's Dictionary
- Build Your Own Video Community With Lighttpd And FlowPlayer (Debian Etch)
- How to perform a point in time restoration using ZRM for MySQL
- Step-by-Step IPP based Print Server using CUPS
- Securing Your Server With A Host-based Intrusion Detection System
- How To Monitor A System With Sysstat On Centos 4.3
- Accessing Windows Or Samba Shares Using AutoFS
Sourceforge
- The Arusha Project (ARK)
- Command Line Progress Bar (bar)
- SMBNetFS — a Linux/FreeBSD filesystem that allow you to use samba/microsoft network in the same manner as the network neighborhood in Microsoft Windows.
Wikipedia
- wikipedia:Category:GNU project software
- wikipedia:GNU Scientific Library
- wikipedia:DotGNU
- wikipedia:Patch_(Unix) (patch)
- wikipedia:Filesystem in Userspace (aka "FUSE")
Other
- Linux-Unix cheat sheets - The ultimate collection
- Unix Toolbox
- shell-fu — collects as many little CLI commands as possible
- phpGroupWare
- HOWTO Auto mount filesystems (AUTOFS)
- sshfs - secure and transparent access to remote filesystems
- Become a digital video editing guru using Linux tools
- nixCraft
- Linux.ie
- 8-Bit ASCII Codes and HTML Equivalents
- RRDtool — data logging and graphing application.
- 15 Javascript Snippets You Can't Live Without
- Kexi Project — "Microsoft Access for Linux"
- The Lazy Guide to Installing Knoppix on a USB Key
- Tracker
- How to Write a Spelling Corrector
- Speaking UNIX, Part 8: UNIX processes
- Free Linux books (on-line only)
- 25 Code Snippets for Web Designers (Part5)
- reCAPTCHA
- JSAN.org &mdsash; JavaScript Archive Network is a comprehensive resource for Open Source JavaScript libraries and software.
- TrueCrypt Tutorial: Truly Portable Data Encryption
- lsof
- jQuery — a fast, concise, JavaScript Library that simplifies how you traverse HTML documents, handle events, perform animations, and add Ajax interactions to your web pages.
- An Introduction to Linux Audio
- Install any Linux distro directly from hard disk without burning any DVD
- Designing Digg Picture Website in a Matter of Hours
- incron — execute commands based on filesystem activity
- Learn 10 good UNIX usage habits
- Carlo Wood's HOWTOs
- Using Mutt with Gmail
- memcachedb — a very fast to get/set an object
- He Sells Shell Scripts to Intersect Sets
- Defragmentation of Linux Filesystems