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.


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.

UpGuard checks and validates configurations for every major OS, network device, and cloud provider.
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

May 19, 2015 - A Look At The New Commandlinefu
I've put together a short writeup on what kind of newness you can expect from the next iteration of clfu. Check it out here.
March 2, 2015 - New Management
I'm Jon, I'll be maintaining and improving clfu. Thanks to David for building such a great resource!
Hide

Top Tags

Hide

Functions

Commands using echo from sorted by
Terminal - Commands using echo - 1,332 results
[command] 2> >(fb=$(dd bs=1 count=1 2>/dev/null | od -t o1 -A n); [ "$fb" ] && err=$(printf "\\${fb# }"; cat) && echo "ERROR - $err")
2017-10-16 22:22:42
User: tyzbit
Functions: dd echo od printf
0

This is a bit of a bash hack to catch STDERR and append a log level to it.

So for example, if your script has pseudo loglevels like so:

echo "INFO - finding files"

[ -f ${files} ] || echo "WARN - no files found"

Any subcommands that write to STDERR will screw that up

Adding 2> >(fb=$(dd bs=1 count=1 2>/dev/null | od -t o1 -A n); [ "$fb" ] && err=$(printf "\\${fb# }"; cat) && echo "ERROR - $err") to the command does the following:

2>

Redirect STDERR

>(

Spawn a subshell (STDERR is then redirected to the file descriptor for this subshell)

fb=$(....)

get the first byte of input

[ "$fb" ]

test if there's a first byte

&& err=$(printf....)

save the output to the $err variable

&& echo "ERROR - $err"

append your pseudo loglevel and the error message

Heavily borrowed from https://unix.stackexchange.com/questions/33049/check-if-pipe-is-empty-and-run-a-command-on-the-data-if-it-isnt

chage -M -1 root; echo "" > /etc/security/opasswd
2017-07-30 21:26:43
User: tsener
Functions: chage echo
0

Disable password expiration and clear password history for VMware vcenter appliance

echo "$(obase=16; echo "$(date +%s)" | bc | xxd -r -p | base32)"
echo "http://commandlinefu.com" | curl -F-=\<- qrenco.de
phase() { while :; do for n in E4 F#4 B4 C#5 D5 F#4 E4 C#5 B4 F#4 D5 C#5; do /usr/bin/play -qn synth $1 pluck $n; done; echo -n "[$1]"; done; }; phase 0.13 & phase 0.131 &
2017-06-14 20:29:26
User: rodolfoap
Functions: echo
0

The Piano Phase piece, by Steve Reich is a minimalist composition which is played on two pianos played at slightly different tempos, a task that's very difficult to accomplish by human players. The auditive effects produced by the cell displacement produce beautiful patterns. See https://en.wikipedia.org/wiki/Piano_Phase . My rendered version: https://ydor.org/SteveReich/piano_phase.mp3

Requires sox to be installed on the system.

There are multiple videos on youtube showing different approaches and experiences to this interpretation. There is also a synthesized version.

Even if Bash can behave as a powerful pianist, a simple threaded version leaves full room to several time glitches and even negative displacements, the same issues that human pianists experience when playing the piece. The older the computer, the better the chaos added to the result due to the CPU load. Apparently that's the reason Steve Reich composes pieces such as this.

Without further ado, please give a warm welcome to the Bash minimalist player on synthesized two-threaded pianos. Please turn off your cellphones.

scrypt(){ [ -n "$1" ]&&{ echo '. <(echo "$(tail -n+2 $0|base64 -d|mcrypt -dq)"); exit;'>$1.scrypt;cat $1|mcrypt|base64 >>$1.scrypt;chmod +x $1.scrypt;};}
2017-06-14 16:27:20
User: rodolfoap
Functions: cat chmod echo
2

This function will encrypt a bash script and will only execute it after providing the passphrase. Requires mcrypt to be installed on the system.

cat hello

#!/bin/bash

case "$1" in

""|-h) echo "This is the fantastic Hello World. Try this:" $(basename $0) "[entity]" ;;

moon) echo Good night. ;;

sun) echo Good morning. ;;

world) echo "Hello, world!" ;;

*) echo Hi, [email protected] ;;

esac

scrypt hello

Enter the passphrase (maximum of 512 characters)

Please use a combination of upper and lower case letters and numbers.

Enter passphrase:

Enter passphrase:

Stdin was encrypted.

cat hello.scrypt

. <(echo "$(/usr/bin/tail -n+2 $0|base64 -d|mcrypt -dq)");exit;

AG0DQHJpam5kYWVsLTEyOAAgAGNiYwBtY3J5cHQtc2hhMQAV34412aaE8sRzQPQzi09YaNQPedBz

aGExAARvB6A/HYValW4txoCFmrlp57lmvhKBbM4p+OUiZcCxr6Y+Mm7ogg3Y14pHi0CrfT70Tubq

9g8/kNJrQr7W/ogHpVuOOdD0YfuRatrV7W2+OlNQ63KX780g4qTHrTqNnyLp8sF5RQ7GwxyZ0Oti

kROtVIU4g4+QAtn/k/e7h7yt4404VF1zzCYRSw20wmJz1o/Z0XO7E/DFBr5Bau7bWjnF7CRVtims

HGrDwv1miTtAcyB9PknymDxhSyjDUdNhqXGBIioUgqjX1CKgedtO0hQp050MiQd3I6HacpSrVUIW

kuuS+BtMrxHDy+48Mh1hidV5JQFP7LP5k+yAVLpeHd2m2eIT1rjVE/Bp2cQVkpODzXcWQDUAswUd

vulvj/kWDQ==

./hello

This is the fantastic Hello World. Try this: hello [entity]

./hello.scrypt

Enter passphrase:

This is the fantastic Hello World. Try this: hello.scrypt [entity]

./hello world

Hello, world!

./hello.scrypt world

Enter passphrase:

Hello, world!

find / -type d | while read i; do ls $i | wc -l | tr -d \\n; echo " -> $i"; done | sort -n
2017-05-12 00:02:43
User: Zort
Functions: echo find ls read sort tr wc
0

Show file count into directories.

Usefull when you try to find hugh directories that elevate system CPU (vmstat -> sy)

printf "%x\n" $(seq 0 255) | xargs -n1 -IH echo -ne \\xH > test.dat
sec2dhms() { declare -i SS="$1" D=$(( SS / 86400 )) H=$(( SS % 86400 / 3600 )) M=$(( SS % 3600 / 60 )) S=$(( SS % 60 )) [ "$D" -gt 0 ] && echo -n "${D}:" [ "$H" -gt 0 ] && printf "%02g:" "$H" printf "%02g:%02g\n" "$M" "$S" }
2017-03-21 23:31:25
User: pdxdoughnut
Functions: echo printf
3

Converts any number of seconds into days, hours, minutes and seconds.

sec2dhms() {

declare -i SS="$1"

D=$(( SS / 86400 ))

H=$(( SS % 86400 / 3600 ))

M=$(( SS % 3600 / 60 ))

S=$(( SS % 60 ))

[ "$D" -gt 0 ] && echo -n "${D}:"

[ "$H" -gt 0 ] && printf "%02g:" "$H"

printf "%02g:%02g\n" "$M" "$S"

}

wait_for_this.sh; echo "wait_for_this.sh finished running" | mail -s "Job Status Update" [email protected]
stf=$(date +%s.%N);for ((;;));do ctf=$( date +%s.%N );echo -en "\r$(date -u -d "0 $ctf sec - $stf sec" "+%H:%M:%S.%N")";done
stf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));do ctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; dtf=$(echo "scale=3; $ctf-$stf" | bc); dt=${dtf/.*/}; dt=${dt:=0};echo -en "\r$(date -u -d @$dt "+%H:%M:%S.${dtf/*./}")";done
stf=$(date +%s.%N);st=${stf/.*/};sn=%{stf/*./};for ((;;));do ctf=$( date +%s.%N );ct=${ctf/.*/};cn=${ctf/*./}; echo -en "\r$(echo "scale=3; $ctf-$stf" | bc)";done
2017-01-26 13:20:30
User: glaudiston
Functions: date echo
Tags: chronometer
0

A way for tracking times in bash

free && sync && echo 3 > /proc/sys/vm/drop_caches && free
printf -vl "%${COLUMNS:-`tput cols 2>&-||echo 80`}s\n" && echo ${l// /-};
2016-09-25 10:37:20
User: AskApache
Functions: echo printf
4

Unlike other methods that use pipes and exec software like tr or sed or subshells, this is an extremely fast way to print a line and will always be able to detect the terminal width or else defaults to 80. It uses bash builtins for printf and echo and works with printf that supports the non-POSIX `-v` option to store result to var instead of printing to stdout.

Here it is in a function that lets you change the line character to use and the length with args, it also supports color escape sequences with the echo -e option.

function L() { local l=; builtin printf -vl "%${2:-${COLUMNS:-`tput cols 2>&-||echo 80`}}s\n" && echo -e "${l// /${1:-=}}"; }

With color:

L "`tput setaf 3`="

1. Use printf to store n space chars followed by a newline to an environment variable "l" where n is local environment variable from $COLUMNS if set, else it will use `tput cols` and if that fails it will default to 80.

2. If printf succeeds then echo `$l` that contains the chars, replacing all blank spaces with "-" (can be changed to anything you want).

From: http://www.askapache.com/linux/bash_profile-functions-advanced-shell.html http://www.askapache.com/linux/bash-power-prompt.html

for y in {1..10}; do for x in {1..10}; do echo -n "| $x*$y=$((y*x)) "; done; echo; done|column -t
2016-09-07 12:31:18
User: lpalgarvio
Functions: column echo
3

The multiplication table for math study

links $( a=( $( lynx -dump -listonly "http://news.google.com" | grep -Eo "(http|https)://[a-zA-Z0-9./?=_-]*" | grep -v "google.com" | sort | uniq ) ) ; amax=${#a[@]} ; n=$(( `date '+%s'` % $amax )) ; echo ${a[n]} )
2016-07-26 11:52:12
User: pascalv
Functions: echo grep sort uniq
2

Access a random news web page on the internet.

The Links browser can of course be replaced by Firefox or any modern graphical web browser.

while true; do A=$(stat -c%s FILE); sleep 1; B=$(stat -c%s FILE); echo -en "\r"$(($B-$A))" Bps"; done
2016-06-27 20:39:06
User: Zort
Functions: echo sleep stat
-2

Muestra el crecimiento de un archivo por segundo.

Cambia el texto "FILE" por el nombre del archivo a monitorear.

Comando STAT

while true; do A=$(ls -l FILE | awk '{print $5}'); sleep 1; B=$(ls -l FILE | awk '{print $5}'); echo -en "\r"$(($B-$A))" Bps"; done
2016-06-27 20:33:02
User: Zort
Functions: awk echo ls sleep
-3

Muestra el crecimiento de un archivo por segundo.

Cambia el texto "FILE" por el nombre del archivo a monitorear.

Comando LS + AWK

echo '"\e\C-i": "\C-awhile true; do ( \C-e ); inotifywait -q -e modify -e close_write *; done\e51\C-b"' >>~/.inputrc
2016-06-10 08:06:50
User: unhammer
Functions: echo
1

Assuming you've written all of

make -j hfst-tokenize && echo doavtter gr?dakursa|./hfst-tokenize --gtd tokeniser-gramcheck-gt-desc.pmhfst

and want that to execute every time you :w in vim (or C-xC-s in Emacs), just hit and it'll turn into

while true; do ( make -j hfst-tokenize && e doavtter gr?dakursa|./hfst-tokenize --gtd tokeniser-gramcheck-gt-desc.pmhfst ); inotifywait -q -e modify -e close_write *; done

with the cursor right before the ')'. Hit enter, and it'll run on each save.

Requires the package inotify-tools installed.

echo "https://www.google.com/maps/place/$(exiftool -ee -p '$gpslatitude, $gpslongitude' -c "%d?%d'%.2f"\" image.jpg 2> /dev/null | sed -e "s/ //g")"
2016-06-09 13:33:10
User: mpb
Functions: echo
3

This command uses the "exiftool" command which is available here: http://www.sno.phy.queensu.ca/~phil/exiftool/

NB, there should be a degree symbol right after the first "%d" NOT a question mark.

For some unknown reason, commandlinefu is not able to handle degree symbol correctly ("?")?

echo "$USER"|rev | espeak
dir=/rom; a=$(find $dir -name \*.sh -exec cat '{}' \; | egrep -cv '^[[:space:]]*#'); b=$(find $dir -name \*.sh -exec cat '{}' \; | egrep -c '^[[:space:]]*#'); echo $((a+b)) lines = ${a} sloc [$((a*100/(a+b)))%] + ${b} comments [$((b*100/(a+b)))%]
scriptName="reorder_files.sh"; echo -e '#!/bin/sh\n' > "${scriptName}"; cat files.txt | while read file; do echo "touch ${file}; sleep 0.5;" >> "${scriptName}"; done; chmod +x "${scriptName}";
2016-04-19 11:52:00
User: programmer
Functions: cat chmod echo read
1

Create a bash script to change the modification time for each file in 'files.txt' such that they are in the same order as in 'files.txt'

File name for bash script specified by variable, 'scriptName'. It is made an executable once writing into it has been completed.

touch files.txt; cat reorder_files.sh | while read line; do x=`echo $line | sed 's/touch \([a-z0-9\.]\+.*.pdf\);.*/\1/'`; echo $x >> files.txt ; done;