Commands tagged printf (41)

  • shorter than alternative


    17
    printf "%`tput cols`s"|tr ' ' '#'
    kamathln · 2010-04-05 17:12:35 9
  • Countdown clock - Counts down from $MIN minutes to zero. I let the date command do the maths. This version doesn't use seq. Show Sample Output


    11
    MIN=10;for ((i=MIN*60;i>=0;i--));do echo -ne "\r$(date -d"0+$i sec" +%H:%M:%S)";sleep 1;done
    flatcap · 2011-02-20 11:56:28 25
  • I love this function because it tells me everything I want to know about files, more than stat, more than ls. It's very useful and infinitely expandable. find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' | sort -rgbS 50% 00761 drwxrw---x askapache:askapache 777:666 [06/10/10 | 06/10/10 | 06/10/10] [d] /web/cg/tmp The key is: # -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n' which believe it or not took me hundreds of tweaking before I was happy with the output. You can easily use this within a function to do whatever you want.. This simple function works recursively if you call it with -r as an argument, and sorts by file permissions. lsl(){ O="-maxdepth 1";sed -n '/-r/!Q1'<<<$@ &&O=;find $PWD $O -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -rgbS 50%; } Personally I'm using this function because: lll () { local a KS="1 -r -g"; sed -n '/-sort=/!Q1' <<< $@ && KS=`sed 's/.*-sort=\(.*\)/\1/g'<<<$@`; find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'|sort -k$KS -bS 50%; } # i can sort by user lll -sort=3 # or sort by group reversed lll -sort=4 -r # and sort by modification time lll -sort=6 If anyone wants to help me make this function handle multiple dirs/files like ls, go for it and I would appreciate it.. Something very minimal would be awesome.. maybe like: for a; do lll $a; done Note this uses the latest version of GNU find built from source, easy to build from gnu ftp tarball. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    8
    find $PWD -maxdepth 1 -printf '%.5m %10M %#9u:%-9g %#5U:%-5G [%AD | %TD | %CD] [%Y] %p\n'
    AskApache · 2010-06-10 22:03:08 8
  • This is super fast and an easy way to test your terminal for 256 color support. Unlike alot of info about changing colors in the terminal, this uses the ncurses termcap/terminfo database to determine the escape codes used to generate the colors for a specific TERM. That means you can switch your terminal and then run this to check the real output. tset xterm-256color at any rate that is some super lean code! Here it is in function form to stick in your .bash_profile aa_256 () { ( x=`tput op` y=`printf %$((${COLUMNS}-6))s`; for i in {0..256}; do o=00$i; echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x; done ) } From my bash_profile: http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    7
    ( x=`tput op` y=`printf %$((${COLUMNS}-6))s`;for i in {0..256};do o=00$i;echo -e ${o:${#o}-3:3} `tput setaf $i;tput setab $i`${y// /=}$x;done; )
    AskApache · 2010-09-06 10:39:27 8
  • This is useful for examining the path. Show Sample Output


    6
    printf ${PATH//:/\\n}
    haivu · 2010-03-26 04:37:33 5
  • Pure Bash This will print a row of characters the width of the screen without using any external executables. In some cases, COLUMNS may not be set. Here is an alternative that uses tput to generate a default if that's the case. And it still avoids using tr. printf -v row "%${COLUMNS:-$(tput cols)}s"; echo ${row// /#} The only disadvantage to either one is that they create a variable. Show Sample Output


    5
    printf -v row "%${COLUMNS}s"; echo ${row// /#}
    dennisw · 2010-04-13 21:56:46 3
  • Useful if you have a list of images called 1 2 3 4 and so on, you can adapt it to rewrite it as 4 (in this example) 0-padded number. Show Sample Output


    5
    for i in ???.jpg; do mv $i $(printf %04d $(basename $i .jpg) ).jpg ; done
    carlesso · 2010-11-18 23:48:41 3
  • A bitcoin "brainwallet" is a secret passphrase you carry in your brain. The Bitcoin Brainwallet Exponent Calculator is one of three functions needed to calculate the bitcoin PRIVATE key. Roughly, the formula is exponent = sha256 (passphrase) Note that this is a bash function, which means you have to type its name to invoke it. You can check the accuracy of the results here http://brainwallet.org Show Sample Output


    5
    function brainwallet_exponent () { printf %s "$1"|sha256sum|head -c 64; }
    nixnax · 2014-02-18 01:49:09 27
  • A bitcoin "brainwallet" is a secret passphrase you carry in your brain. The Bitcoin Brainwallet Exponent Calculator is the second of three functions needed to calculate a bitcoin PRIVATE key. Roughly, checksum is the first 8 hex digits of sha256(sha256(0x80+sha256(passphrase))) Note that this is a bash function, which means you have to type its name to invoke it Show Sample Output


    5
    function brainwallet_checksum () { (o='openssl sha256 -binary'; p='printf';($p %b "\x80";$p %s "$1"|$o)|$o|sha256sum|cut -b1-8); }
    nixnax · 2014-02-18 02:07:02 33
  • An old USB A/B cable is all you need to make your own Smart Home hardware! Cut off and discard the B-portion of the USB cable. On the A side, connect the RED (+) and WHITE (D-) wires via a 1 kiloohm resistor. Picture: http://imgur.com/dJGVlAU Now plug the cable into a USB port on your Linux computer. Your hardware is ready! Run the above command after changing variable mysms to your personal email-to-SMS gateway info as required by your cellular service provider. The command uses the amazing usbmon tool (see link below) to detect the cable. For the curious, to view the raw usbmon output, run this command: (Also see the sample output) usbmon -i usb0 How does it work? When the red and white wires are connected (via the 1 kiloohm resistor) the USB hardwere is tricked into thinking that a new USB device is trying to start up. We then use the usbmon utility to capture the host USB events as it tries to talk to the cable. The expect utility watches the usbmon stream and waits for the disconnect text "-2:128" before sending the SMS message. Finally, the sendmail tool is used to email the SMS message to your smartphone via your cellular provider's SMS-to-email gateway. As a result, when the electrical connection between the red and white wire is interrupted, or the USB cable is unplugged from your computer, you get an SMS notification of the disconnect event on your smartphone. Could this be the cheapest smart home gadget ever? What are YOU going to sense with it? Please let me know in the comments and please don't forget to click it up! Links: http://www.linuxcertif.com/man/8/usbmon/ http://en.wikipedia.org/wiki/USB#Pinouts http://imgur.com/dJGVlAU Show Sample Output


    5
    mysms='xxx0001234@messaging.sprintpcs.com' ; expect -c "log_user 0 ; set timeout -1 ; spawn usbmon -i usb0 ; expect -re \"C.*Ii.*-2:128\" { spawn sendmail $mysms ; send \"Smart Home Sensor Triggered\n.\n\" ; expect }"
    omap7777 · 2015-05-02 06:10:10 14
  • Replace 70 with the desired height. Replace 180 with the desired width. I put it in my bashrc, because by default my terminal is too small.


    4
    printf "\e[8;70;180;t"
    jearsh · 2010-01-07 05:58:16 38
  • 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 Show Sample Output


    4
    printf -vl "%${COLUMNS:-`tput cols 2>&-||echo 80`}s\n" && echo ${l// /-};
    AskApache · 2016-09-25 10:37:20 15
  • Using column to format a directory listing Show Sample Output


    3
    (printf "PERMISSIONS LINKS OWNER GROUP SIZE MONTH DAY HH:MM PROG-NAME\n" \ ; ls -l | sed 1d) | column -t
    opexxx · 2009-10-08 11:53:38 5
  • displays current time in "binary clock" format (loosely) inspired by: http://www.thinkgeek.com/homeoffice/lights/59e0/ "Decoding": 8421 .... - 1st hour digit: 0 *..* - 2nd hour digit: 9 (8+1) .*.. - 1st minutes digit: 4 *..* - 2nd minutes digit: 9 (8+1) Prompt-command version: PROMPT_COMMAND='echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=" ") f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*"' Show Sample Output


    3
    echo "10 i 2 o $(date +"%H%M"|cut -b 1,2,3,4 --output-delimiter=' ') f"|dc|tac|xargs printf "%04d\n"|tr "01" ".*"
    unefunge · 2010-11-24 23:49:21 6

  • 3
    tail -f file |xargs -IX printf "$(date -u)\t%s\n" X
    unefunge · 2010-11-25 11:23:13 5
  • List the full path of some files. You can add ".*" on the end if you want to display hidden files. Show Sample Output


    3
    printf "$PWD/%s\n" *
    flatcap · 2011-12-16 13:43:01 17
  • Draw a telephone keyboard, using just a shell built-in command. Show Sample Output


    3
    printf "%s\t%s\t%s\n" {1..9} '*' 0 '#'
    flatcap · 2014-12-27 11:27:24 14

  • 3
    adb logcat|awk '{ i srand();for (i = 1; i <= NF; i++) { color = int(rand() * 216) + 16; printf "\033[38;5;%dm%s\033[0m ", color, $i;} printf "\n"; }'
    wuseman1 · 2023-05-30 16:48:17 323
  • This one-liner fills the screen with randomly colored lines.


    3
    while :; do printf "\e[48;2;$((RANDOM % 256));$((RANDOM % 256));$((RANDOM % 256))m%*s\e[0m" $(tput cols) ""; sleep 0.1; done
    wuseman1 · 2023-07-04 00:38:46 347
  • This provides a way to sort output based on the length of the line, so that shorter lines appear before longer lines. It's an addon to the sort that I've wanted for years, sometimes it's very useful. Taken from my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    2
    sortwc () { local L;while read -r L;do builtin printf "${#L}@%s\n" "$L";done|sort -n|sed -u 's/^[^@]*@//'; }
    AskApache · 2010-05-20 20:13:52 7
  • One of the first functions programmers learn is how to print a line. This is my 100% bash builtin function to do it, which makes it as optimal as a function can be. The COLUMNS environment variable is also set by bash (including bash resetting its value when you resize your term) so its very efficient. I like pretty-output in my shells and have experimented with several ways to output a line the width of the screen using a minimal amount of code. This is like version 9,000 lol. This function is what I use, though when using colors or other terminal features I create separate functions that call this one, since this is the lowest level type of function. It might be better named printl(), but since I use it so much it's more optimal to have the name contain less chars (both for my programming and for the internal workings). If you do use terminal escapes this will reset to default. tput sgr0 For implementation ideas, check my http://www.askapache.com/linux-unix/bash_profile-functions-advanced-shell.html Show Sample Output


    2
    L(){ l=`builtin printf %${2:-$COLUMNS}s` && echo -e "${l// /${1:-=}}"; }
    AskApache · 2010-06-14 04:35:30 6
  • unset PROMPT_COMMAND to disable. Show Sample Output


    2
    PROMPT_COMMAND='seq $COLUMNS | xargs -IX printf "%Xs\r" @'
    unefunge · 2010-11-24 14:34:21 38
  • Converts IP octets to hex using printf command. Useful for generating pxeboot aliases in the pxelinux.cfg folder. Show Sample Output


    2
    myhex=$(printf '%02X' ${myip//./ };)
    robinsonaarond · 2011-11-30 15:12:28 3
  • Applies each file operator using the built-in test. testt /home/askapache/.sq /home/askapache/.sq -a True - file exists. -d True - file is a directory. -e True - file exists. -r True - file is readable by you. -s True - file exists and is not empty. -w True - the file is writable by you. -x True - the file is executable by you. -O True - the file is effectively owned by you. -G True - the file is effectively owned by your group. -N True - the file has been modified since it was last read. Full Function: testt () { local dp; until [ -z "${1:-}" ]; do dp="$1"; [[ ! -a "$1" ]] && dp="$PWD/$dp"; command ls -w $((${COLUMNS:-80}-20)) -lA --color=tty -d "$dp"; [[ -d "$dp" ]] && find "$dp" -mount -depth -wholename "$dp" -printf '%.5m %10M %#15s %#9u %-9g %#5U %-5G %Am/%Ad/%AY %Cm/%Cd/%CY %Tm/%Td/%TY [%Y] %p\n' -a -quit 2> /dev/null; for f in a b c d e f g h L k p r s S t u w x O G N; do test -$f "$dp" && help test | sed "/-$f F/!d" | sed -e 's#^[\t ]*-\([a-zA-Z]\{1\}\) F[A-Z]*[\t ]* True if#-\1 "'$dp'" #g'; done; shift; done } Show Sample Output


    2
    testt(){ o=abcdefghLkprsStuwxOGN;echo $@;for((i=0;i<${#o};i++));do c=${o:$i:1};test -$c $1 && help test | sed "/^ *-$c/!d;1q;s/^[^T]*/-$c /;s/ if/ -/";done; }
    AskApache · 2012-02-21 16:54:53 8
  • This alias is super-handy for me because it quickly shows the details of each file in the current directory. The output is nice because it is sortable, allowing you to expand this basic example to do something amazing like showing you a list of the newest files, the largest files, files with bad perms, etc.. A recursive alias would be: alias LSR='find -mount -printf "%.5m %10M %#9u:%-9g %#5U:%-5G %TF_%TR %CF_%CR %AF_%AR %#15s [%Y] %p\n" 2>/dev/null' From: http://www.askapache.com/linux/bash_profile-functions-advanced-shell.html Show Sample Output


    2
    alias LS='find -mount -maxdepth 1 -printf "%.5m %10M %#9u:%-9g %#5U:%-5G %TF_%TR %CF_%CR %AF_%AR %#15s [%Y] %p\n" 2>/dev/null'
    AskApache · 2013-02-06 17:54:14 6
  •  1 2 > 

What's this?

commandlinefu.com is the place to record those command-line gems that you return to again and again. 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.

Share Your Commands


Check These Out

force unsupported i386 commands to work on amd64
The above was done using the i386 flashplayer plugin, and was installed on a AMD64 machine running an AMD64 kernel and AMD64 programs. the resulting plugin install ultimately didn't work for swiftfox (but worked for iceweasel) without also covering it with a nspluginwrapper which took a bit of fenangaling to get to work (lots of apt-getting) but it is a nice feature to be able to trick installers that think you need i386 into running on a amd64, or at least attempting to run on amd64. Enjoy

Gets the english pronunciation of a phrase
Usage examples: say hello say "hello world" say hello+world

Generat a Random MAC address
Generate a random MAC address with capital letters

Extract tarball from internet without local saving

Check whether laptop is running on battery or cable
The original proc file doesn't exist on my system.

Install pip with Proxy
Installs pip packages defining a proxy

Track X Window events in chosen window
After executing this, click on a window you want to track X Window events in. Explaination: "xev will track events in the window with the following -id, which we get by greping window information obtained by xwininfo"

dont execute command just add it to history as a comment, handy if your command is not "complete" yet

list files recursively by size

Get the IP address
gives u each configured IP in a seperate line.


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: