Hide

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again.

Delete that bloated snippets file you've been using and share your personal repository with the world. That way others can gain from your CLI wisdom and you from theirs too. All commands can be commented on, discussed and voted up or down.


If you have a new feature suggestion or find a bug, please get in touch via http://commandlinefu.uservoice.com/

Get involved!

You can sign-in using OpenID credentials, or register a traditional username and password.

First-time OpenID users will be automatically assigned a username which can be changed after signing in.

Hide

Stay in the loop…

Follow the Tweets.

Every new command is wrapped in a tweet and posted to Twitter. Following the stream is a great way of staying abreast of the latest commands. For the more discerning, there are Twitter accounts for commands that get a minimum of 3 and 10 votes - that way only the great commands get tweeted.

» http://twitter.com/commandlinefu
» http://twitter.com/commandlinefu3
» http://twitter.com/commandlinefu10

Subscribe to the feeds.

Use your favourite RSS aggregator to stay in touch with the latest commands. There are feeds mirroring the 3 Twitter streams as well as for virtually every other subset (users, tags, functions,…):

Subscribe to the feed for:

Hide

News

2011-03-12 - Confoo 2011 presentation
Slides are available from the commandlinefu presentation at Confoo 2011: http://presentations.codeinthehole.com/confoo2011/
2011-01-04 - Moderation now required for new commands
To try and put and end to the spamming, new commands require moderation before they will appear on the site.
2010-12-27 - Apologies for not banning the trolls sooner
Have been away from the interwebs over Christmas. Will be more vigilant henceforth.
2010-09-24 - OAuth and pagination problems fixed
Apologies for the delay in getting Twitter's OAuth supported. Annoying pagination gremlin also fixed.
Hide

Tags

Hide

Functions

Commands tagged read from sorted by
Terminal - Commands tagged read - 35 results
VAR=$(head -5)
2014-04-05 13:45:18
User: rodolfoap
Functions: head
Tags: read stdin head,
-2

Reads n lines from stdin and puts the contents in a variable. Yes, I know the read command and its options, but find this logical even for one line.

(read -r passphrase; b58encode 80$( brainwallet_exponent "$passphrase" )$( brainwallet_checksum "$passphrase" ))
2

A bitcoin "brainwallet" is a secret passphrase you carry in the "wallet" of your brain.

The Bitcoin Brainwallet Private Key Calculator calculates the standard base58 encoded bitcoin private key from your "brainwallet" passphrase.

The private key is the most important bitcoin number. All other numbers can be derived from it.

This command uses 3 other functions - all 3 are defined on my user page:

1) brainwallet_exponent() - search for Bitcoin Brainwallet Exponent Calculator

2) brainwallet_checksum() - search for Bitcoin Brainwallet Exponent Calculator

3) b58encode() - search for Bitcoin Brainwallet Base58 Encoder

Do make sure you use really strong, unpredictable passphrases (30+ characters)!

http:brainwallet.org can be used to check the accuracy of this calculator.

function b58encode () { local b58_lookup_table=({1..9} {A..H} {J..N} {P..Z} {a..k} {m..z}); bc<<<"obase=58;ibase=16;${1^^}"|(read -a s; for b58_index in "${s[@]}" ; do printf %s ${b58_lookup_table[ 10#"$b58_index" ]}; done); }
2

A bitcoin "brainwallet" is a secret passphrase you carry in your brain.

The Bitcoin Brainwallet Private Key Base58 Encoder is the third of three functions needed to calculate a bitcoin PRIVATE key from your "brainwallet" passphrase.

This base58 encoder uses the obase parameter of the amazing bc utility to convert from ASCII-hex to base58. Tech note: bc inserts line continuation backslashes, but the "read s" command automatically strips them out.

I hope that one day base58 will, like base64, be added to the amazing openssl utility.

read -N1
2013-10-10 10:09:43
User: totti
Functions: read
Tags: read user
6

Usage exaple cmd

echo 'Sure to continue ??'; read -n1 choi; if [ "$choi" = 'y' ] || [ "$choi" = 'Y' ]; then echo -e '\nExecuting..'; else echo 'Aborted'; fi
while read l; do echo -e "$l"; done <1.txt >2.txt
2012-03-13 14:27:49
User: knoppix5
Functions: echo read
Tags: bash read
5

Bash only, no sed, no awk. Multiple spaces/tabs if exists INSIDE the line will be preserved. Empty lines stay intact, except they will be cleaned from spaces and tabs if any available.

while read ; do python <script> ; done
2012-02-23 22:29:09
User: Zulu
Functions: python read
-2

Very useful for test a script. After launch this command, you only have to press ENTER for launch your script again. I work with screen and tape ENTER instead of '!!'+ENTER

If you break your script with CTRL-C, it will wait for press ENTER and will re-launch

You can write like it : while read -p "Press ENTER" ; do python ; done

read day month year < <(date +'%d %m %y')
2011-07-30 06:06:29
User: frans
Functions: date read
Tags: bash read
10

No command substitution but subshell redirection

read day month year <<< $(date +'%d %m %y')
read -s -p"Password: " USER_PASSWORD_VARIABLE; echo
2011-07-20 20:22:42
User: h3nr1x
Functions: read
Tags: read
14

You can ask repeatedly for a non-blank password using this function:

function read_password() {

while [ ! -n "$USER_PASSWORD" ]; do

read -s -p"Password: " USER_PASSWORD

if [ ! -n "$USER_PASSWORD" ]; then

echo "ERROR: You must specify a valid password, please try again"

fi

echo

done

}

Also you can set a time out (in seconds) to write the password

read -t 10 -s -p"Password: " USER_PASSWORD_VARIABLE

if [ ! $? -eq 0 ]; then

echo "Time out!"

fi

find . -type f -name \*.php | while IFS="" read i; do expand -t4 "$i" > "$i-"; mv "$i-" "$i"; done
2011-04-08 12:53:14
User: flatcap
Functions: expand find mv read
-4

Recursively find php files and replace tab characters with spaces.

Options:

"\*.php" -- replace this with the files you wish to find

"expand" -- replace tabs with spaces (use "unexpand" to replace spaces with tabs)

"-t4" -- tabs represent 4 spaces

Note: The IFS="" in the middle is to prevent 'read' from eating leading/trailing whitespace in filenames.

files -type f | xargs -n100 | while read l; do mkdir $((++f)); cp $l $f; done
2011-02-15 23:15:16
User: flatcap
Functions: cp mkdir read xargs
-2

Take a folder full of files and split it into smaller folders containing a maximum number of files. In this case, 100 files per directory.

find creates the list of files

xargs breaks up the list into groups of 100

for each group, create a directory and copy in the files

Note: This command won't work if there is whitespace in the filenames (but then again, neither do the alternative commands :-)

while [ 1 ]; do clear; echo 'YOUR TEXT HERE' | figlet -f banner -t | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done
2011-02-13 18:52:39
User: lkjoel
Functions: banner echo read sleep
-3

Change YOUR TEXT HERE to the text you want.

On figlet -f banner, you can change it to any figlet font you have installed.

One variant for Star Wars fans could be this:

while [ 1 ]; do clear; echo 'Star Wars' | figlet -f starwars -t | while IFS="\n" read l; do echo "$l"; sleep 0.01; done; done

NOTICE: You need to install figlet.

On Ubuntu, this command is:

sudo apt-get install figlet

On Debian, this command is:

aptitude install figlet
cat /dev/sda | pv -r > /dev/null
2011-01-23 22:58:56
User: kerim
Functions: cat
-1

Change your drive letter as you wish.

Using pv command for speed detect.First of all you must install pv command for usage.

http://www.bayner.com/

kerim@bayner.com

read -a ARR <<<'world domination now!'; echo ${ARR[2]};
read -a A<<<".*.**..*....*** 8 9 5 10 6 0 2 11 7 4";for C in `date +"%H%M"|fold -w1`;do echo "${A:${A[C+1]}:4}";done
2010-12-02 22:04:49
User: __
Functions: echo fold read
4

Like 7171, but fixed typo, uses fewer variables, and even more cryptic!

read -a A <<<"8 9 5 10 6 0 3 11 7 4";B='.*.**..*....***';for C in $(date +"%H%M"|fold -w1);do echo "${B:${A[C]}:4}";done
Confirm() { echo -n "$1 [y/n]? " ; read reply; case $reply in Y*|y*) true ;; *) false ;; esac }
2010-11-22 16:54:16
User: eikenberry
Functions: echo false read true
Tags: read
2

This version works across on all POSIX compliant shell variants.

Confirm() { read -sn 1 -p "$1 [Y/N]? "; [[ $REPLY = [Yy] ]]; }
2010-11-22 11:01:14
User: frans
Functions: read
Tags: read
11

Returns true if user presses the key.

Use it like

Confirm "Continue" && do action
for p in `ps L|cut -d' ' -f1`;do echo -e "`tput clear;read -p$p -n1 p`";ps wwo pid:6,user:8,comm:10,$p kpid -A;done
2

While going through the source code for the well known ps command, I read about some interesting things.. Namely, that there are a bunch of different fields that ps can try and enumerate for you. These are fields I was not able to find in the man pages, documentation, only in the source.

Here is a longer function that goes through each of the formats recognized by the ps on your machine, executes it, and then prompts you whether you would like to add it or not. Adding it simply adds it to an array that is then printed when you ctrl-c or at the end of the function run. This lets you save your favorite ones and then see the command to put in your .bash_profile like mine at : http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

Note that I had to do the exec method below in order to pause with read.

t ()

{

local r l a P f=/tmp/ps c='command ps wwo pid:6,user:8,vsize:8,comm:20' IFS=' ';

trap 'exec 66

exec 66 $f && command ps L | tr -s ' ' >&$f;

while read -u66 l >&/dev/null; do

a=${l/% */};

$c,$a k -${a//%/} -A;

yn "Add $a" && P[$SECONDS]=$a;

done

}

statt(){ C=c;stat --h|sed '/Th/,/NO/!d;/%/!d'|while read l;do p=${l/% */};[ $p == %Z ]&&C=fc&&echo ^FS:^;echo "`stat -$C $p \"$1\"` ^$p^${l#%* }";done|column -ts^; }
2010-06-11 23:31:03
User: AskApache
Functions: column read sed
3

This shows every bit of information that stat can get for any file, dir, fifo, etc. It's great because it also shows the format and explains it for each format option.

If you just want stat help, create this handy alias 'stath' to display all format options with explanations.

alias stath="stat --h|sed '/Th/,/NO/!d;/%/!d'"

To display on 2 lines:

( F=/etc/screenrc N=c IFS=$'\n'; for L in $(sed 's/%Z./%Z\n/'<<<`stat --h|sed -n '/^ *%/s/^ *%\(.\).*$/\1:%\1/p'`); do G=$(echo "stat -$N '$L' \"$F\""); eval $G; N=fc;done; )

For a similarly powerful stat-like function optimized for pretty output (and can sort by any field), check out the "lll" function

http://www.commandlinefu.com/commands/view/5815/advanced-ls-output-using-find-for-formattedsortable-file-stat-info

From my .bash_profile ->

http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

sortwc () { local L;while read -r L;do builtin printf "${#L}@%s\n" "$L";done|sort -n|sed -u 's/^[^@]*@//'; }
2010-05-20 20:13:52
User: AskApache
Functions: printf read sed sort
2

This provides a way to sort output based on the length of the line, so that shorter lines appear before longer lines. It's an addon to the sort that I've wanted for years, sometimes it's very useful. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

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'
21

If you have used bash for any scripting, you've used the date command alot. It's perfect for using as a way to create filename's dynamically within aliases,functions, and commands like below.. This is actually an update to my first alias, since a few commenters (below) had good observations on what was wrong with my first command.

# creating a date-based ssh-key for askapache.github.com

ssh-keygen -f ~/.ssh/`date +git-$USER@$HOSTNAME-%m-%d-%g` -C 'webmaster@askapache.com' # /home/gpl/.ssh/git-gplnet@askapache.github.com-04-22-10

# create a tar+gzip backup of the current directory

tar -czf $(date +$HOME/.backups/%m-%d-%g-%R-`sed -u 's/\//#/g' <<< $PWD`.tgz) . # tar -czf /home/gpl/.backups/04-22-10-01:13-#home#gpl#.rr#src.tgz .

I personally find myself having to reference

date --help

quite a bit as a result. So this nice alias saves me a lot of time. This is one bdash mofo. Works in sh and bash (posix), but will likely need to be changed for other shells due to the parameter substitution going on.. Just extend the sed command, I prefer sed to pretty much everything anyways.. but it's always preferable to put in the extra effort to go for as much builtin use as you can. Otherwise it's not a top one-liner, it's a lazyboy recliner.

Here's the old version:

alias dateh='date --help|sed "/^ *%%/,/^ *%Z/!d;s/ \+/ /g"|while read l;do date "+ %${l/% */}_${l/% */}_${l#* }";done|column -s_ -t'

This trick from my [ http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html bash_profile ]

shmore(){ local l L M="`echo;tput setab 4&&tput setaf 7` --- SHMore --- `tput sgr0`";L=2;while read l;do echo "${l}";((L++));[[ "$L" == "${LINES:-80}" ]]&&{ L=2;read -p"$M" -u1;echo;};done;}
2010-04-21 00:40:37
User: AskApache
Functions: echo read
6
SH
cat mod_log_config.c | shmore

or

shmore < mod_log_config.c

Most pagers like less, more, most, and others require additional processes to be loaded, additional cpu time used, and if that wasn't bad enough, most of them modify the output in ways that can be undesirable.

What I wanted was a "more" pager that was basically the same as running:

cat file

Without modifying the output and without additional processes being created, cpu used, etc. Normally if you want to scroll the output of cat file without modifying the output I would have to scroll back my terminal or screen buffer because less modifies the output.

After looking over many examples ranging from builtin cat functions created for csh, zsh, ksh, sh, and bash from the 80's, 90s, and more recent examples shipped with bash 4, and after much trial and error, I finally came up with something that satisifed my objective. It automatically adjusts to the size of your terminal window by using the LINES variable (or 80 lines if that is empty) so

This is a great function that will work as long as your shell works, so it will work just find if you are booted in single user mode and your /usr/bin directory is missing (where less and other pagers can be). Using builtins like this is fantastic and is comparable to how busybox works, as long as your shell works this will work.

One caveat/note: I always have access to a color terminal, and I always setup both the termcap and the terminfo packages for color terminals (and/or ncurses and slang), so for that reason I stuck the

tput setab 4; tput setaf 7

command at the beginning of the function, so it only runs 1 time, and that causes the -- SHMore -- prompt to have a blue background and bright white text.

This is one of hundreds of functions I have in my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html">.bash_profile at http://www.askapache.com/">AskApache.com, but actually won't be included till the next update.

If you can improve this in any way at all please let me know, I would be very grateful! ( Like one thing I want is to be able to continue to the next screen by pressing any key instead of now having to press enter to continue)

while $8;do read n;[ $n = "$l" ]&&c=$(($c+1))||c=0;echo $c;l=$n;done
2010-03-31 00:41:08
User: florian
Functions: read
Tags: bash read Game
1

hold period (or whatever character) and hit enter after a second. You need to make the next line of periods the same length as the previous line... score starts at 0 and increase each time length of line is same.

count="1" ; while true ; do read next ; if [[ "$next" = "$last" ]] ; then count=$(($count+1)) ; echo "$count" ; else count="1" ; echo $count ; fi ; last="$next" ; done
2010-03-30 04:02:29
User: dabom
Functions: echo read true
Tags: bash read Game
8

Really bored during class so I made this...

Basically, you hold period (or whatever) and hit enter after a second and you need to make the next line of periods the same length as the previous line...

My record was 5 lines of the same length.

It's best if you do it one handed with your pointer on period and ring on enter.