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 sh from sorted by
Terminal - Commands using sh - 42 results
$ screen -S test -d -m -- sh -c 'date; exec $SHELL'
2014-02-17 08:11:45
User: awek
Functions: exec screen sh test
0

The command creates new session "test", executes 'date' and then start your default shell (to keep the detached session alive). Change 'date' to fit your needs.

screen -r test

will attach the created session.

find . -type d -maxdepth 1 -print0 | xargs -0 -I{} sh -c 'find "{}" -type f | grep "ogg\|mp3\|wav\|flac$" | wc -l | tr -d "\n"; echo " {}"'
2013-12-22 13:40:29
User: dbrgn
Functions: echo find grep sh tr wc xargs
0

This lists the number of ogg/mp3/wav/flac files in each subdirectory of the current directory. The output can be sorted by piping it into "sort -n".

find -regextype posix-egrep -regex '.*\.(css|js)$' | xargs -I{} sh -c "echo '{}' && yuicompressor '{}' | gzip -c > '{}.gz'"
CSS=$HOME/.config/google-chrome/Default/User\ StyleSheets/Custom.css sh -c 'test -f "$CSS.off" && mv "$CSS.off" "$CSS" || mv "$CSS" "$CSS.off"'
2013-10-06 00:38:00
User: Romero
Functions: mv sh
0

A very simple command to toggle Chrome?s default style sheet. It uses the test command to see if the "Custom.css.off" file exists, if so, it will become "Custom.css", and if not, "Custom.css" is moved to "Custom.css.off" Thus, swapping.

This is accomplished with "&&" and "||"

sh -c 'url="http://youtu.be/MejbOFk7H6c"; vid="`for i in ".*youtu\.be/\([^\/&?#]\+\)" ".*youtu.\+v[=/]\([^\/&?#]\+\)" ".*youtu.\+embed/\([^\/&?#]\+\)"; do expr "${url}" : "${i}"; done`"; if [ -n "${vid}" ]; then echo ${vid}; else echo "${url}"; fi'
2013-09-04 19:33:09
User: qwertyroot
Functions: echo sh
2

url can be like any one of followings:

url="MejbOFk7H6c" url="http://youtu.be/MejbOFk7H6c" url="https://youtube.com/watch?feature=player_embedded&v=MejbOFk7H6c#t" url="//www.youtube.com/v/MejbOFk7H6c?hl=ru_RU&version=3&rel=0" url="http://www.youtube.com/embed/MejbOFk7H6c?feature=player_embedded"

If url mismatching, whole url will be returned.

find . -maxdepth 1 -type d -exec sh -c "printf '{} ' ; find '{}' -type f -ls | wc -l" \;
2013-07-29 19:46:35
User: HerbCSO
Functions: find sh
2

For each directory from the current one, list the counts of files in each of these directories. Change the -maxdepth to drill down further through directories.

find /Applications -type d -maxdepth 1 -exec sh -c 'echo "{}"; (plutil -convert xml1 -o - "{}/Contents/Info.plist" | xpath /dev/stdin "concat(\"v\", /plist/dict/string[preceding-sibling::key[1]=\"CFBundleShortVersionString\"]/node())" 2>/dev/null)' \;
2013-03-29 14:01:23
User: darkfader
Functions: find sh
Tags: osx
-1

Uses find, plutil and xpath.

Note: Some applications don't have proper information. system_profiler might be better to use.

It's a bit slow query.

Due to command length limit, I removed -name "*.app" and CFBundleName.

find . -type f -size +0 -printf "%-25s%p\n" | sort -n | uniq -D -w 25 | sed 's/^\w* *\(.*\)/md5sum "\1"/' | sh | sort | uniq -w32 --all-repeated=separate
2013-02-23 20:44:20
User: jimetc
Functions: find sed sh sort uniq
0

Avoids the nested 'find' commands but doesn't seem to run any faster than syssyphus's solution.

prefix="169.254" && for i in {0..254}; do echo $prefix.$i/8; for j in {1..254}; do sh -c "ping -m 1 -c 1 -t 1 $prefix.$i.$j | grep \"icmp\" &" ; done; done
2012-07-25 12:07:15
User: tempelorg
Functions: echo sh
Tags: ping
0

This version combines the best of the other suggestions and adds these features:

1. It scans a /16 subnet

2. It is very fast by running the ping commands in the background, running them in parallel.

3. Does not use the "-W" option as that's not available in older ping versions (I needed this for OS X 10.5)

find ./ -type f -exec sh -c 'echo "{}" "$(dirname "{}")/$(basename "{}" | tr "[A-Z]" "[a-z]")"' \;
2012-06-14 07:13:42
User: jelloir
Functions: find sh
Tags: bash find mv rename tr
0

Handles spaces in file names and directories. Optionally change directories as well by pipe to tr from dirname.

grep "$1" urls.txt | awk '{print "curl --write-out "$0"=http-%{http_code}\"\n\" --silent --output /dev/null "$0'} | sh >> responses.txt
rlwrap -S "$STY> " sh -c 'while read; do screen -S "'"$STY"'" -X $REPLY; done'
2012-04-16 21:49:06
User: bandie91
Functions: screen sh
Tags: screen rlwrap
0

run it inside a screen session, you send commands to screen itself!

find . -type f \! -name "*.md5" -exec sh -c 'md5sum "$1" > $1.md5' -- {} \;
sh time.sh 1 20 & var1="$!" & sh time.sh 2 10 & var2="$!" & sh time.sh 3 40 & var3="$!" & sh time.sh 4 30 & var4="$!" ; wait $var1 && wait $var2 && wait $var3 && wait $var4
2012-03-31 10:03:58
User: julnegre
Functions: sh wait
0

This command explains how to manage some asynchronous PID in a global process.

The command uses 4 processes in a global process. The asynchronous scripts are simulated by a time.sh script

more infos :

http://code-esperluette.blogspot.fr/2012/03/bash-gestion-de-processus-asynchrones.html

http://www.youtube.com/watch?v=TxsPyAtD70I

adb shell ps | grep my.app.packagename | awk '{print $2}' | xargs -I ? sh -c "adb logcat -v time | grep ?"
pygmentize -l sh ~/.bashrc | less -R
2012-01-27 03:27:37
User: captaincomic
Functions: less sh
0

On Debian/Ubuntu the pygments script is called pygmentize and can be found in the python-pygments package.

For an overview of all available lexers, formatters, styles and filters use

pygmentize -L

Here is an example using more options

pygmentize -f 256 -l sh -F whitespace:spaces=True,tabs=True -O style=borland ~/.bashrc | less -R
sudo sh -c "echo '127.0.0.1 www.facebook.com' >> /etc/hosts"
2012-01-16 14:06:51
User: devalnor
Functions: sh sudo
6

or

echo '127.0.0.1 facebook.com' | sudo tee -a /etc/hosts

Do not execute this command if you don't know what you are doing.

lso(){ jot -w '%04d' 7778 0000 7777 |sed '/[89]/d;s,.*,printf '"'"'& '"'"';chmod & '"$1"';ls -l '"$1"'|sed s/-/./,' \ |sh \ |{ echo "lso(){";echo "ls \$@ \\";echo " |sed '";sed 's, ,@,2;s,@.*,,;s,\(.* \)\(.*\),s/\2/\1/,;s, ,,';echo \';echo };};}
2012-01-08 05:48:24
User: argv
Functions: chmod echo ls sed sh
0

this requires the use of a throwaway file.

it outputs a shell function.

assuming the throwaway file is f.tmp

usage: >f.tmp;lso f.tmp > f.tmp; . f.tmp;rm f.tmp;lso -l ...

notes:

credit epons.org for the idea. however his version did not account for the sticky bit and other special cases.

many of the 4096 permutations of file permissions make no practical sense. but chmod will still create them.

one can achieve the same sort of octal output with stat(1), if that utility is available.

here's another version to account for systems with seq(1) instead of jot(1):

lso(){

case $# in

1)

{ case $(uname) in

FreeBSD)

jot -w '%04d' 7778 0000 7777 ;;

*)

seq -w 0000 7777 ;;

esac; } \

|sed '

/[89]/d

s,.*,printf '"'"'& '"'"';chmod & '"$1"';ls -l '"$1"'|sed s/-/./,' \

|sh \

|{

echo "lso(){";

echo "ls \$@ \\";

echo " |sed '";

sed '

s, ,@,2;

s,@.*,,;

s,\(.* \)\(.*\),s/\2/\1/,;

s, ,,';

echo \';

echo };

};

;;

*)

echo "usage: lso tmp-file";

;;

esac;

}

this won't print out types[1]. but its purpose is not to examine types. its focus is on mode and its purpose is to make mode easier to read (assuming one finds octal easier to read).

1. one could of course argue "everything is a file", but not always a "regular" one. e.g., a "directory" is really just a file comprising a list.

sudo sh -c 'gunzip -c source.gz > destination'
2011-07-05 23:51:01
User: UnixNeko
Functions: sh sudo
0

Extracting .gz files and placing the output in another directory in one command line is convenient thing.

I just followed some how-to to install Nagios on Ubuntu Lucid Lynx but they give the method to install from archives. I wished to install from the repository. If you do so some files are missing. I've not tested yet but this is an example command line I did to extract

sudo sh -c 'gunzip -c /usr/share/doc/nagios3-common/examples/template-object/templates.cfg.gz > /etc/nagios3/objects/templates.cfg'

We need privilege to write the destination file.

find . -name '*.epub' -exec sh -c 'a={}; ebook-convert $a ${a%.epub}.mobi --still --more --options' \;
2011-04-21 22:03:01
User: joedhon
Functions: find sh
0

-exec sh -c 'var={}; do something with var' lets you do things in a sub-shell

while it's faster to type, I'm not sure if dozens of subshells execute quicker than the while loops.

find . -name "*.java" -type f -perm +600 -print | xargs -I _ sh -c 'grep -q hexianmao _ && iconv -f gb2312 -t utf8 -o _ -c _ '
2011-03-08 13:02:25
User: Sunng
Functions: find iconv sh xargs
Tags: find xargs iconv
-1

One of my friends committed his code in the encoding of GB2312, which broke the build job. I have to find his code and convert.

svn status | grep '^?' | sed -e 's/^? */svn add "/g' -e 's/$/"/g'|sh ; svn status | grep '^!' | sed -e 's/^! */svn delete "/g' -e 's/$/"/g'|sh
sudo sh /usr/share/doc/libdvdread4/install-css.sh
ontouchdo(){ while :; do a=$(stat -c%Y "$1"); [ "$b" != "$a" ] && b="$a" && sh -c "$2"; sleep 1; done }
2010-10-22 23:25:12
User: putnamhill
Functions: sh sleep stat
Tags: stat
10

This is useful if you'd like to see the output of a script while you edit it. Each time you save the file the command is executed. I thought for sure something like this already exists - and it probably does. I'm on an older system and tend to be missing some useful things.

Examples:

ontouchdo yourscript 'clear; yourscript somefiletoparse'

Edit yourscript in a separate window and see new results each time you save.

ontouchdo crufty.html 'clear; xmllint --noout crufty.html 2>&1 | head'

Keep editing krufty.html until the xmllint window is empty.

Note: Mac/bsd users should use stat -f%m. If you don't have stat, you can use perl -e '$f=shift; @s=stat($f); print "$s[9]\n";' $1

cd /proc&&ps a -opid=|xargs -I+ sh -c '[[ $PPID -ne + ]]&&echo -e "\n[+]"&&tr -s "\000" " "<+/cmdline&&echo&&tr -s "\000\033" "\nE"<+/environ|sort'
1

Grabs the cmdline used to execute the process, and the environment that the process is being run under. This is much different than the 'env' command, which only lists the environment for the shell. This is very useful (to me at least) to debug various processes on my server. For example, this lets me see the environment that my apache, mysqld, bind, and other server processes have.

Here's a function I use:

aa_ps_all () { ( cd /proc && command ps -A -opid= | xargs -I'{}' sh -c 'test $PPID -ne {}&&test -r {}/cmdline&&echo -e "\n[{}]"&&tr -s "\000" " "<{}/cmdline&&echo&&tr -s "\000\033" "\nE"<{}/environ|sort&&cat {}/limits' ); }

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