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 bash from sorted by
Terminal - Commands tagged bash - 695 results
:!bash
2012-08-13 17:13:53
User: CLIxBOBxBOM
Tags: bash vim vi
2

Helps when I'm editing a script and want to double check some commands without having to exit out of vi multiple times or having to use another terminal session.

alias irc="screen -D -R -S chatclient irssi"
2012-08-12 13:24:43
User: expelledboy
Functions: alias
2

This command attempts to attach to existing irssi session, if one exists, otherwise creates one.

I use "irc" because I use different irc clients depending on what system I am working on. Consistency is queen.

for folder in $( find $( pwd ) -maxdepth 1 -type d | grep -v .svn ); do svn propset svn:ignore -F ignorelist ${folder}; done
2012-08-03 13:50:45
User: Highwayman
Functions: find grep pwd
Tags: bash
0

To use this comment you'll have to create a file entitled 'ignorelist' where you put the file name or pattern of the files you want to ignore. I used it for my maven project which generates the child project files in each folder so I can import them into eclipse. By adding these project files to the ignore list ensure they won't appear each time I run 'svn status'.

egrep '.*(("STATUS)|("HEAD)).*' http_access.2012.07.18.log | awk '{sum+=$11; ++n} END {print "Tot="sum"("n")";print "Avg="sum/n}'
2012-07-27 12:18:29
User: fanchok
Functions: awk egrep
0

Depending on your Apache access log configuration you may have to change the sum+=$11 to previous or next awk token.

Beware, usually in access log last token is time of response in microseconds, penultimate token is size of response in bytes. You may use this command line to calculate sum and average of responses sizes.

You can also refine the egrep regexp to match specific HTTP requests.

eselect bashcomp enable --global $(eselect bashcomp list | sed -e 's/ //g'| cut -d']' -f2 | sed -e 's/\*//'| xargs)
set -x && PS4='+\t '
umount -a -t cifs
up() { [ $(( $1 + 0 )) -gt 0 ] && cd $(eval "printf '../'%.0s {1..$1}"); }
2012-06-15 17:10:45
User: Mozai
Functions: cd eval
Tags: bash cd
6

`up 3` will climb the directory tree by three steps. `up asdf` will do nothing, and returns exit code 1 as an error should.

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.

stty -ixon
2012-05-28 19:04:19
User: ricardofunke
Functions: stty
1

This command disable sending of start/stop characters.

It's useful when you want to use incremental reverse history search forward shortcut (Ctrl+s).

To enable again, type:

stty -ixoff
bind -P
2012-05-28 18:51:59
User: ricardofunke
38

This command shows the various shortcuts that can be use in bash, including Ctrl+L, Ctrl+R, etc...

You can translate "\C-y" to Ctrl+y, for example.

desiredDay=6; year=2012; month=5; n=0; while [ $(date -d "$year-$((month+1))-1 - $n day" "+%u") -ne $desiredDay ]; do n=$((n+1)); done; date -d "$year-$((month+1))-1 - $n day" "+%x"
2012-05-17 12:02:30
Functions: date
0

Choosing your year and month. You only need the gnu date command and bash. desiredDay of the week is (1..7); 1 is Monday.

If you want desiredDay of week (0..6); 0 is Sunday

desiredDay=6; year=2012; month=5; n=0; while [ $(date -d "$year-$((month+1))-1 - $n day" "+%w") -ne $desiredDay ]; do n=$((n+1)); done; date -d "$year-$((month+1))-1 - $n day" "+%x"
export PROMPT_COMMAND=$PROMPT_COMMAND'; export PWD_UPCASE="${PWD^^}"'; export PS1='C:${PWD_UPCASE//\\//\\\\}>'
2012-04-30 20:09:49
User: chungy
Functions: export
0

(This may be specific to bash only.) This transforms the current working directory to all uppercase characters and replaces forward slashes with backslashes, prepending the string with "C:" and appending a single ">". It serves no practical purpose, but may serve as a great practical joke if you can insert it to some victim's .bashrc :-)

compgen -c | sort -u > commands && less commands
ls ${PATH//:/ }
2012-04-26 19:45:52
User: Zulu
Functions: ls
9

List all commands present on system by folder.

PATH contains all command folder separated by ':'. With ${PATH//:/ }, we change ':' in space and create a list of folder for ls command.
<ctrl+r>
2012-04-15 16:42:32
User: moollaza
1

"What it actually shows is going to be dependent on the commands you've previously entered.

When you do this, bash looks for the last command that you entered that contains the substring "ls", in my case that was "lsof ...". If the command that bash finds is what you're looking for, just hit Enter to execute it. You can also edit the command to suit your current needs before executing it (use the left and right arrow keys to move through it).

If you're looking for a different command, hit Ctrl+R again to find a matching command further back in the command history. You can also continue to type a longer substring to refine the search, since searching is incremental.

Note that the substring you enter is searched for throughout the command, not just at the beginning of the command." - http://www.linuxjournal.com/content/using-bash-history-more-efficiently

for k in $(git branch | sed /\*/d); do echo "$(git log -1 --pretty=format:"%ct" $k) $k"; done | sort -r | awk '{print $2}'
2012-04-07 11:19:00
User: dahuie
Functions: awk echo sed sort
Tags: bash git sed awk
0

Simpler and without all of the coloring gimmicks. This just returns a list of branches with the most recent first. This should be useful for cleaning your remotes.

eval <command> ${INBACK:-&}
2012-04-05 03:50:57
User: Zulu
Functions: eval
Tags: bash eval nohup
-1

If $INBACK is set, command will launch in foreground and inverse.

Very useful in script !

We could apply the inverse comportement like that :

eval command ${INBACK:+&}

sudo dpkg-reconfigure keyboard-configuration
2012-03-27 21:07:45
Functions: sudo
1

Bash snippet to force GNU/Linux keyboard settings, layout and configuration.

Usefull when some GNU/Linux distributions such as *Ubuntu's store only limited configation options due to demonstration purposes on LiveUSB or Live persistent devices.

Overcomes the English QWERTY to French AZERTY settings failure.

Code bash en ligne de commande pour forcer l'adoption du clavier AZERTY sur les cl? USB bootable en Ubuntu.

tail() { thbin="/usr/bin/tail"; if [ "${1:0:1}" != "-" ]; then fc=$(($#==0?1:$#)); lpf="$((($LINES - 3 - 2 * $fc) / $fc))"; lpf="$(($lpf<1?2:$lpf))"; [ $fc -eq 1 ] && $thbin -n $lpf "$@" | /usr/bin/fold -w $COLUMNS | $thbin -n $lpf || $thbin -n $lpf...
2012-03-23 19:00:30
User: fpunktk
Functions: tail
-1
tail() { thbin="/usr/bin/tail"; if [ "${1:0:1}" != "-" ]; then fc=$(($#==0?1:$#)); lpf="$((($LINES - 3 - 2 * $fc) / $fc))"; lpf="$(($lpf<1?2:$lpf))"; [ $fc -eq 1 ] && $thbin -n $lpf "$@" | /usr/bin/fold -w $COLUMNS | $thbin -n $lpf || $thbin -n $lpf "$@"; else $thbin "$@"; fi; unset lpf fc thbin; }

This is a function that implements an improved version of tail. It tries to limit the number of lines so that the screen is filled completely. It works with pipes, single and multiple files. If you add different options to tail, they will overwrite the settings from the function.

It doesn't work very well when too many files (with wrapped lines) are specified.

Its optimised for my three-line prompt.

It also works for head. Just s/tail/head/g

Don't set 'thbin="tail"', this might lead to a forkbomb.

alias tail='tail -n $((${LINES:-`tput lines 2>/dev/null||echo -n 80`} - 7))'
2012-03-22 02:44:11
User: AskApache
Functions: alias echo
2

Run the alias command, then issue

ps aux | tail

and resize your terminal window (putty/console/hyperterm/xterm/etc) then issue the same command and you'll understand.

${LINES:-`tput lines 2>/dev/null||echo -n 12`}

Insructs the shell that if LINES is not set or null to use the output from `tput lines` ( ncurses based terminal access ) to get the number of lines in your terminal. But furthermore, in case that doesn't work either, it will default to using the default of 80.

The default for TAIL is to output the last 10 lines, this alias changes the default to output the last x lines instead, where x is the number of lines currently displayed on your terminal - 7. The -7 is there so that the top line displayed is the command you ran that used TAIL, ie the prompt.

Depending on whether your PS1 and/or PROMPT_COMMAND output more than 1 line (mine is 3) you will want to increase from -2. So with my prompt being the following, I need -7, or - 5 if I only want to display the commandline at the top. ( http://www.askapache.com/linux/bash-power-prompt.html )

275MB/748MB

[7995:7993 - 0:186] 06:26:49 Thu Apr 08 [askapache@n1-backbone5:/dev/pts/0 +1] ~

In most shells the LINES variable is created automatically at login and updated when the terminal is resized (28 linux, 23/20 others for SIGWINCH) to contain the number of vertical lines that can fit in your terminal window. Because the alias doesn't hard-code the current LINES but relys on the $LINES variable, this is a dynamic alias that will always work on a tty device.

for w in $(tr 'A-Z ,."()?!;:' 'a-z\n' < sample.txt); do echo ${#w} $w; done | sort -u | sort -n
2012-03-15 14:14:11
User: flatcap
Functions: echo sort tr
Tags: bash sort tr
0

Take a file and ,."()?!;: give a list of all the words in order of increasing length.

First of all use tr to map all alphabetic characters to lower case and also strip out any puntuation.

A-Z become a-z

,."()?!;: all become \n (newline)

I've ignored - (hyphen) and ' (apostrophe) because they occur in words.

Next use bash to print the length ${#w} and the word

Finally sort the list numerically (sort -n) and remove any duplicates (sort -u).

Note: sort -nu performs strangely on this list. It outputs one word per length.

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.

for ((x=0;;x+=5)); do sleep 5; hours=$(($x/3600)); minutes=$(($x%3600/60)); seconds=$(($x%60)); echo "$hours hours $minutes minutes $seconds seconds have elapsed" | festival --tts & done
2012-03-06 22:58:43
User: mrklaw
Functions: echo sleep
0

Says time every 5 seconds in hours, minutes and seconds using festival.

for ((x=0;;x+=5)); do sleep 5; echo $x | festival --tts & done
2012-03-06 21:17:51
User: mrklaw
Functions: echo sleep
0

works the same, but uses festival instead of espeak