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 eval from sorted by
Terminal - Commands using eval - 43 results
( eval $(grep -z '^DBUS_SESSION_BUS_ADDRESS' /proc/$(pgrep -u $USER plasma-overlay)/environ); export DBUS_SESSION_BUS_ADDRESS; kquitapp plasma-overlay )
2014-09-01 12:49:58
User: mig_hg
Functions: eval export grep
0

So this first obtains address of the DBUS session, as it's not available by default over SSH. Then it tells plasma-overlay to exit. `kquitapp` is pretty much an equivalent of the qdbus calls.

eval echo $(echoprint-codegen "/path/to/file.mp3"| jq ' .[0].metadata | "mp3info -a \"" + .artist + "\" -t \"" + .title + "\" -l \"" + .release + "\" \"" + .filename + "\"" ' ) | bash
2014-08-08 21:14:53
User: glaudiston
Functions: echo eval
0

echoprint identify your song, then return artist, song name and album name(release) in a JSON. jq parse it and mp3info set the data in your mp3 file.

of course it depends on:

mp3info

jq

echoprint

You need to set the environment variable

export CODEGEN_NEST_API_KEY='YOUR_ECHONEST_KEY_HERE'

You can use it with find, but probably will bypass the 120 request/minute of developer account key. So, use a sleep to do it.

Something like:

find -name \*.mp3 | while read $f; do eval echo $(echoprint-codegen "$f" | jq ' .[0].metadata | "mp3info -a \"" + .artist + "\" -t \"" + .title + "\" -l \"" + .release + "\" \"" + .filename + "\"" ' ) | bash; sleep 1; done
eval $(history | cut -c 8- | grep "adb connect [0-9]" | tail -1)
2014-02-27 14:44:27
User: CanOrhan
Functions: cut eval grep tail
0

Connects to the last adb connection in history.

$(eval "echo {${min}..${max}}")
for i in {1..6};do c=;d=;for u in `eval echo {1..$i}`;do c="$c../";d="$d..";eval "$d(){ cd $c;}"; eval "$d.(){ cd $c;}";done;done
2013-09-04 20:12:45
User: bbbco
Functions: echo eval
Tags: cd eval dot
1

Use dots to cd down directories instead of having to remember all of the pesky back slashes!

Better yet, works on even and odd number of dots! Now, just estimate how far down you want to traverse.

alias timer='export ts=$(date +%s);p='\''$(date -u -d @"$(($(date +%s)-$ts))" +"%H.%M.%S")'\'';watch -n 1 -t banner $p;eval "echo $p"'
2013-08-24 16:18:45
User: ichbins
Functions: alias banner date eval watch
Tags: timer banner
1

Starts and shows a timer. banner command is a part of the sysvbanner package. Instead of the banner an echo or figlet commands could be used. Stop the timer with Ctrl-C and elapsed time will be shown as the result.

eval `ls -1d * | awk '{print "zip -r "$1".zip "$1";"}'`
function up { cd $(eval printf '../'%.0s {1..$1}) && pwd; }
2013-01-21 12:57:45
User: michelsberg
Functions: cd eval printf
Tags: cd directory
5

Usage:

up N

I did not like two things in the submitted commands and fixed it here:

1) If I do cd - afterwards, I want to go back to the directory I've been before

2) If I call up without argument, I expect to go up one level

It is sad, that I need eval (at least in bash), but I think it's safe here.

eval is required, because in bash brace expansion happens before variable substitution, see http://rosettacode.org/wiki/Repeat_a_string#Using_printf

while true;do n="$(curl -s http://news.yahoo.com/rss/|sed 's/</\n/g'|grep "title>"|sed -e '/^\// d' -e 's/title>/---------- /g' -e '1,3d'|tr '\n' ' ')";for i in $(eval echo {0..${#n}});do echo -ne "\e[s\e[0;0H${n:$i:$COLUMNS}\e[u";sleep .15;done;done &
2012-11-17 23:56:17
User: SQUIIDUX
Functions: echo eval sleep
7

This creates a permanent stock ticker in the terminal. it has scrolling action and refreshes when each cycle is done to get the latest news.

function mkdircd () { mkdir -p "$@" && eval cd "\"\$$#\""; }
2012-06-26 17:19:16
User: ankush108
Functions: cd eval mkdir
Tags: cd mkdir
0

Creates a directory and then cds into it directly

index=twitter geo.coordinates{}="*"| spath path=geo.coordinates{} output=geocoordinates| eval latitude=mvindex(geocoordinates,1)| eval longitude=mvindex(geocoordinates,0)
2012-06-19 02:57:40
User: SplunkNinja
Functions: eval
Tags: splunk
0

If you're using GNIP as as data source provider for Twitter data in their "Activity Streams" format, use this search to pull out the geo coordinates from tweets as "latitude & longitude". You'll find that splunk creates a "multivalued" field out of the "geo.coordinates{}" field from a tweet. A mulitvalued field is an array, so by using "mvindex(field,position_in_array_starting_with_zero), we can create new fields on the fly for lat/lon.

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.

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:+&}

watch() { while true; do echo "<Ctrl+V><Ctrl+L>Every 2.0s: $@"; date; eval "$@"; sleep 2; done }
2012-03-07 09:30:15
User: hfs
Functions: echo eval sleep watch
Tags: watch
0

Usage:

watch ls -l

Basic but usable replacement for the "watch" command for those systems which don't have it (e.g. the Solaris I'm trapped on).

Type Ctrl+V to escape the following Ctrl+L which clears the screen. It will be displayed as "^L".

for i in `seq 0 9` A B C D E F; do for j in `seq 0 9` A B C D E F; do HEX=\$\'\\x${i}${j}\'; if ! eval grep -qF "$HEX" file; then eval echo $HEX \\x${i}${j}; fi; done; done 2> /dev/null | less
2012-01-05 10:09:07
User: moogmusic
Functions: echo eval grep
0

Scan a file and print out a list of ASCII characters that are not used in the file which can then be safely used to delimit fields. Useful when needing to convert CSV files using "," to a single character delimiter. Piping it into less at the end (which could be redundant) stops the command characters being interpreted by the terminal.

function eve (); { eval "print -s ${1?no variable}=\'\$$1\'" }
2012-01-03 17:03:00
User: libdave
Functions: eval
2

This only makes sense if you are using command line editing.

Create the function in your current zsh session, then type

eve PATH

go 'UP' in your history and notice the current (editable) definition of PATH shows up as the previous

command.

Same as doing:

PATH="'$PATH'"

but takes fewer characters and you don't have to remember the escaping.

c="cp -a";e="~";echo -e "\npaste\n";i=0;k="1"; while [[ "$k" != "" ]]; do read -a k;r[i]=$k;((i++));done;i=0;while :;do t=${r[i]};[ "$t" == "" ] && break; g=$(echo $c ${r[i]} $e);echo -e $g "\ny/n?";read y;[ "$y" != "n" ] && eval $g;((i++));done
2011-12-04 12:45:44
User: knoppix5
Functions: echo eval read
-1

Schematics:

command [options] [paste your variable here] parameter

command [options] [paste entire column of variables here] parameter

...

(hard-code command "c" and parameter "e" according to your wishes: in example shown command = "cp -a" and parameter = "~")

Features:

- Quick exchange only variable part of a long command line

- Make variable part to be an entire column of data (i.e. file list)

- Full control while processing every single item

Hints:

Paste column of data from anywhere. I.e. utilize the Block Select Mode to drag, select and copy columns (In KDE Konsole with Ctrl+Alt pressed, or only Ctrl pressed in GNOME Terminal respectively).

Disadvantages:

You can paste only one single variable in a row. If there are more space separated variables in a row only first one will be processed, but you can arrange your variables in a column instead. To transpose rows to columns or vice versa look at Linux manual pages for 'cut' and 'paste'.

TODO:

- add edit mode to vary command "c" and parameter "e" on the fly

- add one edit mode more to handle every list item different

- add y/n/a (=All) instead of only y(=default)/n to allowed answers

Disclaimer:

The code is not optimized, only the basic idea is presented here. It's up to you to shorten code or extend the functionality.

ack-open () { local x="$(ack -l $* | xargs)"; if [[ -n $x ]]; then eval vim -c "/$*[-1] $x"; else echo "No files found"; fi }
2011-10-04 08:56:18
User: iynaix
Functions: echo eval vim
1

Takes the same arguments that ack does. E.g. ack-open -i "searchterm" opens all files below the current directory containing the search term. The search term is also highlighted within vim if you have hlsearch set. Works on zsh, unsure if it works on bash.

Note: ubuntu users have to change ack to ack-grep unless you already have it aliased (as I do)

isdef() { eval test -n \"\${$1+1}\"; }
eval $(date +"day=%d; month=%m; year=%y")
2011-07-29 12:47:26
User: xakon
Functions: date eval
Tags: bash eval
4

It's quite easy to capture the output of a command and assign it in a shell's variable:

day=$(date +%d) month=$(date +%m)

But, what if we want to perform the same task with just one program invocation? Here comes the power of eval! date(1) outputs a string like "day=29; month=07; year=11" (notice the semicolons I added on purpose at date's custom output) which is a legal shell line. This like is then parsed and executed by the shell once again with the help of eval. Just setting 3 variables!

Inspired by LinuxJournal's column "Dave Taylor's Work the Shell".

eval "mkdir test{$(seq -s, 1 10)}"
2011-07-23 17:09:01
User: xakon
Functions: eval
Tags: bash seq eval
0

In order to create, let's say, 10 directories with a single process we can use the command:

mkdir test{1,2,3,4,5,6,7,8,9,10}

something extremely boring to type! Why not use seq?

seq -s, 1 10

and use its output inside the curly braces?

The obvious solution

mkdir test{$(seq -s, 1 10)}

is, unfortunately, too naive and doesn't work. The answer is the order of the shell expansions (feature of Bourne Shell, actually), where brace expansion happens before command substitution (according to Bash's manual).

The solution is to put another level of substitution, using the powerful and mystic command eval.

I found the trick in a similar problem in the post at http://stackoverflow.com/questions/6549037/bash-brace-expansion-in-scripts-not-working-due-to-unwanted-escaping

eval ls -l /proc/{$(pgrep -d, COMMAND)}/cwd
2011-04-14 13:41:58
User: splante
Functions: eval ls
3

This is an alternative to another command using two xargs. If it's a command you know there's only one of, you can just use:

ls -l /proc/$(pgrep COMMAND)/cwd
getarray(){ a=$1;b="${a[$2]}";eval "c=$b";echo "${c[$3]}";return 0;};a[0]="( a b c )";a[1]="( d e f )";getarray a 1 2
l=10;for((i=0;i<$l;i++));do eval "a$i=($(pv=1;v=1;for((j=0;j<$l;j++));do [ $i -eq 0 -o $j -eq 0 ]&&{ v=1 && pv=1; }||v=$((pv+a$((i-1))[$((j))]));echo -n "$v ";pv=$v;done;));";eval "echo \"\${a$i[@]}\"";done | column -t;
to() { eval dir=\$$1; cd "$dir"; }
2010-10-15 13:40:35
User: hfs
Functions: cd eval
4

Set a bookmark as normal shell variable

p=/cumbersome/path/to/project

To go there

to p

This saves one "$" and is faster to type ;-) The variable is still useful as such:

vim $p/<TAB>

will expand the variable (at least in bash) and show a list of files to edit.

If setting the bookmarks is too much typing you could add another function

bm() { eval $1=$(pwd); }

then bookmark the current directory with

bm p