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 using printf from sorted by
Terminal - Commands using printf - 154 results
while true; do printf "\e[32m%X\e[0m" $((RANDOM%2)); for ((i=0; i<$((RANDOM%128)); i++)) do printf " "; done; done
2012-11-27 10:40:42
User: seb1245
Functions: printf
0

Unlike other alternatives, this command only relies on bash builtins and should also work on windows platforms with the bash executable.

Sparseness corresponds to the number 128 and can be adjusted. To print all possible digits instead of only 0 and 1 replace RANDOM%2 by RANDOM%10 or RANDOM%16 to add letters [A-F].

hl-nonprinting () { local C=$(printf '\033[0;36m') B=$(printf '\033[0;46m') R=$(printf '\033[0m') np=$(env printf "\u00A0\uFEFF"); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/" -e "s/[$np]/${B}& $R/g";}
2012-11-07 10:09:40
User: unhammer
Functions: env printf sed
-1

Can't see it here, but the non-breaking space is highlighted :)

Of course,

cat -t -e

achieves something similar, but less colourful.

Could add more code points from https://en.wikipedia.org/wiki/Space_%28punctuation%29#Spaces_in_Unicode

hl-nonprinting () { local C=$(printf '\033[0;36m') R=$(printf '\033[0m'); sed -e "s/\t/${C}&#9657;&$R/g" -e "s/$/${C}&#8267;$R/";}
2012-11-07 09:55:48
User: unhammer
Functions: printf sed
-1

I don't think it's possible to give a (background) colour to the tab itself, since a tab is, IIUC, simply a command to the terminal to move to the right. Nevertheless, this "highlighting" can be helpful when working with tab-separated files.

for i in `ls /var/log/sa/|grep -E "sa[0-9][0-9]"`;do echo -ne "$i -- ";sar -r -f /var/log/sa/$i|awk '{ printf "%3.2f\n",($4-$6-$7)*100/(3+$4)}'|grep -Eiv "average|linux|^ --|0.00|^-" |awk '{sum+=$1 }END{printf "Average = %3.2f%%\n",sum/NR}';done
/sbin/ifconfig |awk '/bond|eth/{getline i;printf $0" ";printf "%s\n", i" "}'|awk '{print $1,substr($7,6)}'
find -maxdepth 3 -type d | while read -r dir; do printf "%s:\t" "$dir"; find "$dir" | wc -l; done
2012-10-15 15:00:09
User: brainstorm
Functions: find printf read wc
1

Counts the files present in the different directories recursively. One only has to change maxdepth to have further insight in the directory hierarchy.

Found at unix.stackexchange.com:

http://unix.stackexchange.com/questions/4105/how-do-i-count-all-the-files-recursively-through-directories

echo -e "\e[32m"; while :; do printf '%*c' $(($RANDOM % 30)) $(($RANDOM % 2)); done
2012-09-25 17:36:25
Functions: echo printf
Tags: random Matrix
3

Prints 0's and 1's in The Matrix style. You can easily modify to print 0-9 digits using $RANDOM %10 insted of %2.

grep -H voluntary_ctxt /proc/*/status |gawk '{ split($1,proc,"/"); if ( $2 > 10000000 ) { printf $2 " - Process : "; system("ps h -o cmd -p "proc[3]) } }' | sort -nk1,1 | sed 's/^/Context Switches: /g'
2012-09-01 19:43:47
User: jperkster
Functions: gawk grep printf sed sort
0

This command will find the highest context switches on a server and give you the process listing.

for ((i=65;i<91;i++)); do printf "\\$(printf '%03o' $i) "; done
alarmclock() { [ $1 ] || echo Parameter TIME is missing. 1>&2 && return 1 ; ( sleep $1 ; for x in 9 8 7 6 5 4 3 2 1 ; do for y in `seq 0 $[ 10 - $x ] ` ; do printf "\a"; sleep 0.$x ; done ; done ) & }
2012-08-16 15:35:15
User: lkj
Functions: echo printf return sleep
0

usage: alarmclock TIME

TIME is a sleep(1) parameter which tells function how long to wait until raise the alarm.

printf "%s," "${LIST[@]}" | cut -d "," -f 1-${#LIST[@]}
2012-06-04 14:56:12
User: Valise
Functions: cut printf
0

printf reapeats the format as longer as it has arguments. Then the idea is to make cut retain as much fields as we have elements in the array.

As usual with such join/split string manipulation, you have to make sure you don't have conflicts between your separator and your array content.

find /proc/sys/vm -maxdepth 1 -type f | while read i ; do printf "%-35s\t%s\n" "$i" "$(<$i)" ; done | sort -t/ -k4
2012-05-25 16:34:16
User: SEJeff
Functions: find printf read sort
0

Sometimes you want to see all of the systcls for a given $thing. I happened to need to easily look at all of the vm sysctls between two boxes and compare them. This is what I came up with.

members () { dscl . -list /Users | while read user; do printf "$user "; dsmemberutil checkmembership -U "$user" -G "$*"; done | grep "is a member" | cut -d " " -f 1; };
2012-05-20 11:34:33
User: eduo
Functions: cut grep printf read
-1

Group membership in OS X is a mish-mash of standards that end up meaning there's almost a half-dozen of ways to belong to a group, what with group inheritance and automatic assignment. This means there's no easy command to find out all groups a user belongs to. The only sensible way then is to list all users and then query each user for membership.

NOTE: This is a function. Once input you can execute it by calling with a groupname.

printf "%$(tput cols)s\n"|tr ' ' '='
2012-04-21 23:26:55
Functions: printf tr
9

Use tput cols to find the width of the terminal and set it as the minimum field width.

yes "$(seq 232 255;seq 254 -1 233)" | while read i; do printf "\x1b[48;5;${i}m\n"; sleep .01; done
_p(){ ps ax |grep $1 |sed '/grep.'"$1"'/d' |while read a;do printf ${a%% *}' ';printf "${a#* }" >&2;printf '\n';done;}
2012-04-01 19:46:19
User: argv
Functions: grep printf ps read sed
0

proc lister

usage: p

proc killer

usage: p patt [signal]

uses only ps, grep, sed, printf and kill

no need for pgrep/pkill (not part of early UNIX)

_p(){

ps ax \

|grep $1 \

|sed '

/grep.'"$1"'/d' \

|while read a;do

printf ${a%% *}' ';

printf "${a#* }" >&2;

printf '\n';

done;

}

p(){

case $# in

0)

ps ax |grep .|less -iE;

;;

1)

_p $1;

;;

[23])

_p $1 2>/dev/null \

|sed '/'"$2"'/!d;

s,.*,kill -'"${3-15}"' &,'|sh -v

;;

esac;

}

alas, can't get this under 255 chars.

flatcap?

_p(){ ps ax |grep $1 |sed '/grep.'"$1"'/d' |while read a;do printf ${a%% *}' ';printf "${a#* }" >&2;printf '\n';done;}
2012-04-01 19:45:17
User: argv
Functions: grep printf ps read sed
0

proc lister

usage: p

proc killer

usage: p patt [signal]

uses only ps, grep, sed, printf and kill

no need for pgrep/pkill (not part of early UNIX)

_p(){

ps ax \

|grep $1 \

|sed '

/grep.'"$1"'/d' \

|while read a;do

printf ${a%% *}' ';

printf "${a#* }" >&2;

printf '\n';

done;

}

p(){

case $# in

0)

ps ax |grep .|less -iE;

;;

1)

_p $1;

;;

[23])

_p $1 2>/dev/null \

|sed '/'"$2"'/!d;

s,.*,kill -'"${3-15}"' &,'|sh -v

;;

esac;

}

alas, can't get this under 255 chars.

flatcap?

find /path/to/dir -iname "*.ext" -print0 | xargs -0 mplayer -really-quiet -cache 64 -vo dummy -ao dummy -identify 2>/dev/null | awk '/ID_LENGTH/{gsub(/ID_LENGTH=/,"")}{SUM += $1}END{ printf "%02d:%02d:%02d\n",SUM/3600,SUM%3600/60,SUM%60}'
2012-03-11 12:28:48
User: DarkSniper
Functions: awk find printf xargs
0

Improvement on Coderjoe's Solution. Gets rid of grep and cut (and implements them in awk) and specifies some different mplayer options that speed things up a bit.

du -k | sort -n | perl -ne 'if ( /^(\d+)\s+(.*$)/){$l=log($1+.1);$m=int($l/log(1024)); printf ("%6.1f\t%s\t%25s %s\n",($1/(2**(10*$m))),(("K","M","G","T","P")[$m]),"*"x (1.5*$l),$2);}' | more
2012-02-07 15:49:19
User: Q_Element
Functions: du perl printf sort
0

This one line Perl script will display the smallest to the largest files sizes in all directories on a server.

genRandomText() { x=({a..z}); for(( i=0; i<$1; i++ )); do printf ${x[$((RANDOM%26))]}; done; printf "\n"; }
2012-01-26 08:19:33
User: uxseven
Functions: printf
0

Here's my version. It's a bit lengthy but I prefer it since it's all Bash.

VAR="%23%21%2fbin%2fbash" ; printf -v VAR "%b" "${VAR//\%/\x}" ; echo $VAR
2012-01-06 22:09:01
User: Corona688
Functions: echo printf
Tags: bash urldecod
5

You can use ordinary printf to convert "%23%21%2fbin%2fbash" into "#!/bin/bash" with no external utilities, by using a little known printf feature -- the "%b" specifier converts shell escapes. Replace % with \x and printf will understand the urlencoded string.

BASH's printf has an extension to set a variable directly, too. So you get to convert urlencoded strings from garble to plaintext in one step with no externals and no backticks.

printf "$PWD/%s\n" *
2011-12-16 13:43:01
User: flatcap
Functions: printf
Tags: printf
3

List the full path of some files.

You can add ".*" on the end if you want to display hidden files.

hex() { printf "%X\n" $1; }
mplayer -endpos 0.1 -vo null -ao null -identify *.avi 2>&1 |grep ID_LENGTH |cut -d = -f 2|awk '{SUM += $1} END { printf "%d:%d:%d\n",SUM/3600,SUM%3600/60,SUM%60}'
awk 'BEGIN{FS=":"; print "digraph{"}{split($4, a, ","); for (i in a) printf "\"%s\" [shape=box]\n\"%s\" -> \"%s\"\n", $1, a[i], $1}END{print "}"}' /etc/group|display
2011-12-04 01:56:44
Functions: awk printf
19

Parses /etc/group to "dot" format and pases it to "display" (imagemagick) to show a usefull diagram of users and groups (don't show empty groups).