Commands tagged bash (821)

  • Thanks for the submit! My alternative produces summaries only for directories. The original post additionally lists all files in the current directory. Sometimes the files, they just clutter up the output. Once the big directory is located, *then* worry about which file(s) are consuming so much space.


    -1
    du -kd | egrep -v "/.*/" | sort -n
    rmbjr60 · 2010-03-30 15:40:35 3
  • The shell has perfectly adequate pattern matching for simple expressions. Show Sample Output


    -1
    function ends_in_y() { case $(date +%A) in *y ) true ;; * ) false ;; esac } ; ends_in_y && echo ok
    unixmonkey9199 · 2010-04-06 22:18:52 3
  • Essentially the same as funky's alias, but will not traverse filesystems and has nicer formatting. Show Sample Output


    -1
    alias dush="du -xsm * | sort -n | awk '{ printf(\"%4s MB ./\",\$1) ; for (i=1;i<=NF;i++) { if (i>1) printf(\"%s \",\$i) } ; printf(\"\n\") }' | tail"
    dopeman · 2010-07-15 10:38:27 4
  • forces user to rw, group to r, and other to no access. files will not be marked executable. directories will be executable for users and groups only. Show Sample Output


    -1
    chmod -R u=rw-x+X,g=r-x+X,o= .
    donnoman · 2010-07-16 18:42:00 5
  • Output the html from xkcd's index.html, filter out the html tags, and then view it in gwenview. Show Sample Output


    -1
    gwenview `wget -O - http://xkcd.com/ | grep 'png' | grep '<img src="http://imgs.xkcd.com/comics/' | sed s/title=\".*//g | sed 's/.png\"/.png/g' | sed 's/<img src=\"//g'`
    hunterm · 2010-08-24 22:21:51 4
  • Shorter version with curl and awk


    -1
    eog `curl 'http://xkcd.com/' | awk -F "ng): |</h" '/embedding/{print $2}'`
    dog · 2010-08-25 14:04:30 3
  • It works in every linux box Show Sample Output


    -1
    cat /proc/cpuinfo
    magicjohnson_ · 2010-09-24 09:27:58 3
  • The command was too long for the command box, so here it is: echo $(( `wget -qO - http://i18n.counter.li.org/ | grep 'users registered' | sed 's/.*\<font size=7\>//g' | tr '\>' ' ' | sed 's/<br.*//g' | tr ' ' '\0'` + `curl --silent http://www.dudalibre.com/gnulinuxcounter?lang=en | grep users | head -2 | tail -1 | sed 's/.*<strong>//g' | sed 's/<\/strong>.*//g'` )) This took me about an hour to do. It uses wget and curl because, dudalibre.com blocks wget, and wget worked nicely for me. Show Sample Output


    -1
    Check the Description below.
    hunterm · 2010-10-07 04:22:32 3
  • Often times you run a command in the terminal and you don't realize it's going to take forever. You can open a new terminal, but you lose the local history of the suspended one. You can stop the running command using , but that may produce undesirable side-effects. suspends the job, and (assuming you have no other jobs running in the background) %1 resumes it. Appending & tells it to run in the background. You now have a job running concurrently with your terminal. Note this will still print any output to the same terminal you're working on. Tested on zsh and bash. Show Sample Output


    -1
    <ctrl+z> %1 &
    joem86 · 2010-10-25 17:43:38 5
  • Just added view with the eog viewer.


    -1
    wget -O xkcd_$(date +%y-%m-%d).png `lynx --dump http://xkcd.com/|grep png`; eog xkcd_$(date +%y-%m-%d).png
    theanalyst · 2010-10-27 13:42:55 3
  • Uses xargs to call the second grep with the first grep's results as arguments


    -1
    grep -l bar *.log | xargs grep -l foo
    dlebauer · 2011-01-10 19:54:46 3
  • This will tighten up security for your box. The default value for PermitRootLogin sadly is 'yes'.


    -1
    s=/etc/ssh/sshd_config;r=PermitRootLogin;cp $s{,.old}&& if grep $r $s;then sed "s/$r yes/$r no/" $s.old > $s; else echo $r no >> $s;fi
    kzh · 2011-01-30 23:41:59 11
  • Here's a bash version using an array.


    -1
    a=(*); echo ${a[$((RANDOM % ${#a[@]}))]}
    putnamhill · 2011-03-18 13:24:52 3
  • Sometimes you might need to have two copies of data that is in tar. You might unpack, and then copy, but if IO is slow, you might lower it by automatically writing it twice (or more times)


    -1
    mkdir copy{1,2}; gzip -dc file.tar.gz | tee >( tar x -C copy1/ ) | tar x -C copy2/
    depesz · 2011-04-14 17:02:05 5

  • -1
    echo $(( $( date +%s ) - $( stat -c %Y * | sort -nr | head -n 1 ) ))
    depesz · 2011-05-12 14:29:45 3
  • urldecode files in current directrory


    -1
    ls * | while read fin;do fout=$(echo -n $fin | sed -e's/%\([0-9A-F][0-9A-F]\)/\\\\\x\1/g' | xargs echo -e);if [ "$fout" != "$fin" ];then echo "mv '$fin' '$fout'";fi;done | bash -x
    pawelb1973 · 2011-05-18 07:24:54 80
  • Newer versions of Dropbox let you choose the location for your Dropbox folder. If you use script to put things into your Dropbox folder (todo list, screenshots, torrents etc.) but have the Dropbox folder in different locations on your other computers this lets you use the same script on all systems without having to tell it where the Dropbox folder is. Show Sample Output


    -1
    sqlite3 $HOME/.dropbox/config.db "select value from config where key like '%dropbox_path%'"
    mobilediesel · 2011-06-05 08:26:02 13
  • Outputs the real time it takes a Redis ping to run in thousands of a second without any proceeding 0's. Useful for logging or scripted action.


    -1
    TIME=$( { time redis-cli PING; } 2>&1 ) ; echo $TIME | awk '{print $3}' | sed 's/0m//; s/\.//; s/s//; s/^0.[^[1-9]*//g;'
    allrightname · 2011-08-11 19:09:49 4

  • -1
    RANGE=`wc -l /usr/share/dict/words | sed 's/^\([0-9]*\) .*$/\1/'`; for i in {1..4}; do let "N = $RANDOM % $RANGE"; sed -n -e "${N}p" /usr/share/dict/words | tr -d '\n'; done; RANGE=100; let "N = $RANDOM % $RANGE"; echo $N
    unixmonkey24597 · 2011-08-16 07:04:57 3
  • uses fifo and sets to a specific port. In this case 4201.


    -1
    mkfifo ._b; nc -lk 4201 0<._b | /bin/bash &>._b;
    gt · 2011-08-21 05:22:41 3
  • This is an "argument calculator" funktion. The precision is set to 4 and you can use dot (.) or comma (,) as decimal mark (which is great for german users with a comma on the numpad).


    -1
    calc() { echo "scale=4; ${*//,/.}" | bc -l; }
    fpunktk · 2011-10-24 19:58:20 4
  • 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. Show Sample Output


    -1
    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
    knoppix5 · 2011-12-04 12:45:44 4
  • Mac install ssh-copy-id From there on out, you would upload keys to a server like this: (make sure to double quote the full path to your key) ssh-copy-id -i "/PATH/TO/YOUR/PRIVATE/KEY" username@server or, if your SSH server uses a different port (often, they will require that the port be '2222' or some other nonsense: (note the double quotes on *both* the "/path/to/key" and "user@server -pXXXX"): ssh-copy-id -i "/PATH/TO/YOUR/PRIVATE/KEY" "username@server -pXXXX" ...where XXXX is the ssh port on that server


    -1
    sudo curl "http://hg.mindrot.org/openssh/raw-file/c746d1a70cfa/contrib/ssh-copy-id" -o /usr/bin/ssh-copy-id && sudo chmod 755 /usr/bin/ssh-copy-id
    misterich · 2012-02-09 20:29:24 5
  • You need to have mtr installed on your host.


    -1
    mtr google.com
    d_voge · 2012-02-19 22:27:48 3
  • 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.


    -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...
    fpunktk · 2012-03-23 19:00:30 3
  • ‹ First  < 27 28 29 30 31 >  Last ›

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

Replicate a directory structure dropping the files

find out how many days since given date
You can also do this for seconds, minutes, hours, etc... Can't use dates before the epoch, though.

Count number of files in subdirectories
For each directory from the current one, list the counts of files in each of these directories. Change the -maxdepth to drill down further through directories.

Adequately order the page numbers to print a booklet
Useful if you don't have at hand the ability to automatically create a booklet, but still want to. F is the number of pages to print. It *must* be a multiple of 4; append extra blank pages if needed. In evince, these are the steps to print it, adapted from https://help.gnome.org/users/evince/stable/duplex-npage.html.en : 1) Click File ▸ Print. 2) Choose the General tab. Under Range, choose Pages. Type the numbers of the pages in this order (this is what this one-liner does for you): n, 1, 2, n-1, n-2, 3, 4, n-3, n-4, 5, 6, n-5, n-6, 7, 8, n-7, n-8, 9, 10, n-9, n-10, 11, 12, n-11... ...until you have typed n-number of pages. 3) Choose the Page Setup tab. - Assuming a duplex printer: Under Layout, in the Two-side menu, select Short Edge (Flip). - If you can only print on one side, you have to print twice, one for the odd pages and one for the even pages. In the Pages per side option, select 2. In the Page ordering menu, select Left to right. 4) Click Print.

Sort files by date
Show you the list of files of current directory sorted by date youngest to oldest, remove the 'r' if you want it in the otherway.

Convert CSV to JSON
Replace 'csv_file.csv' with your filename.

reverse-i-search: Search through your command line history
"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

Get the list of local files that changed since their last upload in an S3 bucket
Can be useful to granulary flush files in a CDN after they've been changed in the S3 bucket.

print DateTimeOriginal from EXIF data for all files in folder
see output from `identify -verbose` for other keywords to filter for (e.g. date:create, exif:DateTime, EXIF:ExifOffset).

Change every instance of OLD to NEW in file FILE
Very quick way to change a word in a file. I use it all the time to change variable names in my PHP scripts (sed -i 's/$oldvar/$newvar/g' index.php)


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: