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

Convert seconds to [DD:][HH:]MM:SS
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" }

Visit wikileaks.com
Who needs a DNS server

resume other user's screen session via su, without pty error
Normally, if you su to another user from root and try to resume that other user's screen session, you will get an error like "Cannot open your terminal '/dev/pts/0' - please check." This is because the other user doesn't have permission for root's pty. You can get around this by running a "script" session as the new user, before trying to resume the screen session. Note you will have to execute each of the three commands separately, not all on the same line as shown here. Credit: I found this at http://www.hjackson.org/blog/archives/2008/11/29/cannot-open-your-terminal-dev-pts-please-check.

Place the NUM-th argument of the most recent command on the shell
After executing a command with multiple arguments like cp ./temp/test.sh ~/prog/ifdown.sh you can paste any argument of the previous command to the console, like ls -l ALT+1+. is equivalent to ls -l ./temp/test.sh ALT+0+. stands for command itself ('ls' in this case) Simple ALT+. cycles through last arguments of previous commands.

Get your external IP address without curl
Curl is not installed by default on many common distros anymore. wget always is :) $ wget -qO- ifconfig.me/ip

power off system in X hours form the current time, here X=2

awk date convert
Convert readable date/time with `date` command

Alias TAIL for automatic smart output
Run the alias command, then issue $ps aux | tail and resize your terminal window (putty/console/hyperterm/xterm/etc) then issue the same command and you'll understand. $ ${LINES:-`tput lines 2>/dev/null||echo -n 12`} Insructs the shell that if LINES is not set or null to use the output from `tput lines` ( ncurses based terminal access ) to get the number of lines in your terminal. But furthermore, in case that doesn't work either, it will default to using the default of 80. The default for TAIL is to output the last 10 lines, this alias changes the default to output the last x lines instead, where x is the number of lines currently displayed on your terminal - 7. The -7 is there so that the top line displayed is the command you ran that used TAIL, ie the prompt. Depending on whether your PS1 and/or PROMPT_COMMAND output more than 1 line (mine is 3) you will want to increase from -2. So with my prompt being the following, I need -7, or - 5 if I only want to display the commandline at the top. ( http://www.askapache.com/linux/bash-power-prompt.html ) 275MB/748MB [7995:7993 - 0:186] 06:26:49 Thu Apr 08 [askapache@n1-backbone5:/dev/pts/0 +1] ~ $ In most shells the LINES variable is created automatically at login and updated when the terminal is resized (28 linux, 23/20 others for SIGWINCH) to contain the number of vertical lines that can fit in your terminal window. Because the alias doesn't hard-code the current LINES but relys on the $LINES variable, this is a dynamic alias that will always work on a tty device.

generate a unique and secure password for every website that you login to
usage: sitepass MaStErPaSsWoRd example.com description: An admittedly excessive amount of hashing, but this will give you a pretty secure password, It also eliminates repeated characters and deletes itself from your command history. tr '!-~' 'P-~!-O' # this bit is rot47, kinda like rot13 but more nerdy rev # this avoids the first few bytes of gzip payload, and the magic bytes.

Route outbound SMTP connections through a addtional IP address rather than your primary


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: