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 - 715 results
echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n|sed 1q` `who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `ps aux|wc -l`]\007"
2009-09-19 06:57:53
User: AskApache
Functions: echo
4

I usually have 5 or more ssh connections to various servers, and putting this command in my .bash_profile file makes my putty window or x terminal window title change to this easily recognizable and descriptive text. Includes the username, group, server hostname, where I am connecting from (for SSH tunneling), which device pts, current server load, and how many processes are running.

You can also use this for your PROMPT_COMMAND variable, which updates the window title to the current values each time you exec a command.

I prefix running this in my .bash_profile with

[[ ! -z "$SSH_TTY" ]] &&

which makes sure it only does this when connecting via SSH with a TTY.

Here's some rougher examples from http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html

# If set, the value is executed as a command prior to issuing each primary prompt. #H=$((hostname || uname -n) 2>/dev/null | sed 1q);W=$(whoami) #export PROMPT_COMMAND='echo -ne "\033]0;${W}@${H}:${PWD/#$HOME/~} ${SSH_TTY/\/dev\//} [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"`]\007"' #PROMPT_COMMAND='echo -ne "\033]0;`id -un`:`id -gn`@`hostname||uname -n 2>/dev/null|sed 1q` `command who -m|sed -e "s%^.* \(pts/[0-9]*\).*(\(.*\))%[\1] (\2)%g"` [`uptime|sed -e "s/.*: \([^,]*\).*/\1/" -e "s/ //g"` / `command ps aux|wc -l`]\007"' #[[ -z "$SSH_TTY" ]] || export PROMPT_COMMAND #[[ -z "$SSH_TTY" ]] && [[ -f /dev/stdout ]] && SSH_TTY=/dev/stdout

And here's a simple function example for setting the title:

function set_window_title(){ echo -e "\033]0; ${1:-$USER@$HOST - $SHLVL} \007"; }
for p in ${PATH//:/ }; do [[ -d $p && -x $p ]] && echo $p; done
2009-09-19 06:43:57
User: AskApache
Functions: echo
1

Finds executable and existing directories in your path that can be useful if migrating a profile script to another system. This is faster and smaller than any other method due to using only bash builtin commands.

See also:

+ http://www.commandlinefu.com/commands/view/743/list-all-execs-in-path-usefull-for-grepping-the-resulting-list

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

printf "%02u " {3..20}; echo
2009-09-18 18:48:41
User: Escher
Functions: printf
Tags: bash strings
0

emulates bash4's "echo {03..20}"

Uses bash3 builtin function printf

for s in `seq -f %02.0f 5 15`; do echo $s; done
2009-09-18 13:21:38
User: Yeraze
Functions: echo
Tags: bash seq
0

Uses 'seq' with formatting parameter to generate the necessary padded sequence. Change '%02.0f' to how many digits you need (for 3, use %03.0f, etc) and replace 5 & 15 with your desired min and max.

for i in {0..1}{0..9}; do echo $i; done
2009-09-18 02:51:12
User: dennisw
Functions: echo
Tags: bash strings
-1

Bash 4 will let you do {00..19} to get leading zeros, but Bash 3 doesn't have that feature. This technique gets you partway there (the sequences need be such that the last digit ranges from zero to nine - you can't use this for something like Bash 4's {03..27}, for example). When this limitation is not a problem, you can avoid some complicated string manipulation for concatenating leading zeros.

You can add more digits like this: {0..1}{0..9}{0..9} (ranges from 0 to 99 with up to two leading zeros). To pad with additional zeros:

for i in 000{0..1}{0..9}; do echo $i; done

or

for i in {0..1}{0..9}; do echo "000$i"; done

This is useful for creating values to sort or for creating filenames with a fixed format. Note that this will also work:

touch {0..1}{0..9}
budir=/tmp/bu.$$;for name in repMainPath/*/format;do dir=${name%/format};bufil=dumpPath/${dir##*/};svnadmin hotcopy --clean-logs $dir $budir;svnadmin dump --delta $budir>$bufil;rm -rf $budir;done
2009-09-16 01:34:48
User: arcege
Functions: dump
Tags: bash svn
2

Use of hotcopy for safety/stability of the backups.

find repMainPath -maxdepth 1 -mindepth 1 -type d | while read dir; do echo processing $dir; sudo svnadmin dump --deltas $dir >dumpPath/`basename $dir`; done
2009-09-15 20:14:51
User: Marco
Functions: dump echo find read sudo
Tags: bash svn
2

This command dumps all SVN repositories inside of folder "repMainPath" (not recursively) to the folder "dumpPath", where one dump file will be created for each SVN repository.

function nowrap { export COLS=`tput cols` ; cut -c-$COLS ; unset COLS ; }
function sepath { echo $PATH |tr ":" "\n" |sort -u |while read L ; do cd "$L" 2>/dev/null && find . \( ! -name . -prune \) \( -type f -o -type l \) 2>/dev/null |sed "s@^\./@@" |egrep -i "${*}" |sed "s@^@$L/@" ; done ; }
2009-09-11 15:03:22
User: mobidyc
Functions: cd echo egrep find read sed sort tr
Tags: bash ksh PATH
-1

search argument in PATH

accept grep expressions

without args, list all binaries found in PATH

PS3="Enter a number: "; select f in *;do $EDITOR $f; break; done
2009-09-10 06:04:42
User: haivu
Tags: bash
8

This command displays a simple menu of file names in the current directory. After the user made a choice, the command invokes the default editor to edit that file.

* Without the break statement, the select command will loop forever

* Setting the PS3 prompt is optional

* If the user types an invalid choice (such as the letter q), then the variable $f will become an empty string.

* For more information, look up the bash's select command

echo $PATH | tr \: \\n
2009-09-09 02:10:04
User: crk
Functions: echo tr
Tags: bash echo tr PATH
12

This version uses Pipes, but is easier for the common user to grasp... instead of using sed or some other more complicated method, it uses the tr command

some_very_long_and_complex_command # label
2009-09-08 05:58:27
User: jamolkhon
79

When using reverse-i-search you have to type some part of the command that you want to retrieve. However, if the command is very complex it might be difficult to recall the parts that will uniquely identify this command. Using the above trick it's possible to label your commands and access them easily by pressing ^R and typing the label (should be short and descriptive).

UPDATE:

One might suggest using aliases. But in that case it would be difficult to change some parts of the command (such as options, file/directory names, etc).

find . -regex '.*\(h\|cpp\)'
2009-09-06 11:33:19
User: Vereb
Functions: find
Tags: bash find
7

This is the way how you can find header and cpp files in the same time.

watch -n <seconds> <command>
du -a --max-depth=1 | sort -n | cut -d/ -f2 | sed '$d' | while read i; do if [ -f $i ]; then du -h "$i"; else echo "$(du -h --max-depth=0 "$i")/"; fi; done
2009-09-03 20:43:43
User: nickwe
Functions: cut du echo read sed sort
3

Based on the MrMerry one, just add some visuals to differentiate files and directories

find . -maxdepth 1 -type d|xargs du -a --max-depth=0|sort -rn|cut -d/ -f2|sed '1d'|while read i;do echo "$(du -h --max-depth=0 "$i")/";done;find . -maxdepth 1 -type f|xargs du -a|sort -rn|cut -d/ -f2|sed '$d'|while read i;do du -h "$i";done
2009-09-03 20:33:21
User: nickwe
Functions: cut du echo find read sed sort xargs
2

Based on the MrMerry one, just add some visuals and sort directory and files

function checkfor () { while :; do $*; sleep 5; done; }
2009-09-03 19:35:42
User: relay
Functions: sleep
Tags: bash
1

checkfor: have the shell check anything you're waiting for.

'while : ; do' is an infinite loop

'$*' executes the command passed in

'sleep 5' - change for your tastes, sleep for 5 seconds

bash, ksh, likely sh, maybe zsh

Ctrl-c to break the loop

function fcd () { [ -f $1 ] && { cd $(dirname $1); } || { cd $1 ; } pwd }
2009-09-03 18:58:13
User: relay
Functions: cd dirname pwd
Tags: bash ksh
1

fcd : file change directory

A bash function that takes a fully qualified file path and cd's into the directory where it lives. Useful on the commadline when you have a file name in a variable and you'd like to cd to the directory to RCS check it in or look at other files associated with it.

Will run on any ksh, bash, likely sh, maybe zsh.

echo "${PATH//:/$'\n'}"
for i in 192.168.1.{61..71};do ping -c 1 $i &> /dev/null && echo $i;fi;done
2009-08-26 06:04:24
User: AlecSchueler
Functions: echo ping
Tags: Network ssh bash
-2

If you need to ssh into a computer on the local network but you're unsure of the ip to use, then ping them and see if you get a response. If you do, print out the address you got it from. Adjust the range to suit your network.

for file in <filename>; do cp $file{,.bak} && sed 's/old/new/g' $file.bak > $file; done
2009-08-25 16:19:45
User: Cenobite
Functions: cp file sed
Tags: bash sed
0

"&&" runs sed if and only if the backup completed and /bin/cp exited cleanly. Works for multiple files; just specify multiple filenames (or glob). Use -v switch for cp to play it safe.

eval $(sed -n "s/^d[^D]*DB_\([NUPH]\)[ASO].*',[^']*'\([^']*\)'.*/_\1='\2'/p" wp-config.php) && mysqldump --opt --add-drop-table -u$_U -p$_P -h$_H $_N | gpg -er AskApache >`date +%m%d%y-%H%M.$_N.sqls`
2009-08-18 07:03:08
User: AskApache
Functions: eval gpg sed
3

The coolest way I've found to backup a wordpress mysql database using encryption, and using local variables created directly from the wp-config.php file so that you don't have to type them- which would allow someone sniffing your terminal or viewing your shell history to see your info.

I use a variation of this for my servers that have hundreds of wordpress installs and databases by using a find command for the wp-config.php file and passing that through xargs to my function.

IFS=:; find $PATH | grep pattern
2009-08-14 13:38:58
User: camspiers
Functions: find grep
Tags: bash find grep
1

Best to put it in a file somewhere in your path. (I call the file spath)

#!/bin/bash

IFS=:; find $PATH | grep $1

Usage: $ spath php

id="dMH0bHeiRNg";mplayer -fs http://youtube.com/get_video.php?video_id=$id\&t=$(curl -s http://www.youtube.com/watch?v=$id | sed -n 's/.*, "t": "\([^"]*\)", .*/\1/p')
2009-08-13 14:16:01
User: matthewbauer
Functions: id sed
12

The original doesn't work for me - but this does. I'm guessing that Youtube updated the video page so the original doesn't work.

not necessarily better, but many...!
2009-08-12 11:03:26
Tags: bash awk
-17

( IFS=:; for i in $PATH; do echo $i; done; )

echo $PATH|sed -e 's/:/\n/g' # but the tr one is even better of course

echo $PATH|xargs -d: -i echo {} # but this comes up with an extra blank line; can't figure out why and don't have the time :(

echo $PATH|cut -d: --output-delimiter='

' -f1-99 # note -- you have to hit ENTER after the first QUOTE, then type the second one. Sneaky, huh?

echo $PATH | perl -l -0x3a -pe 1 # same darn extra new line; again no time to investigate

echo $PATH|perl -pe 's/:/\n/g' # too obvious; clearly I'm running out of ideas :-)