Commands tagged bash (762)

  • Reads a username from Show Sample Output

    read -p 'Username: ' u;sudo -H -u $u xauth add $(xauth list|grep :$(echo ${DISPLAY: -4:2}));sudo su - $u
    vutcovici · 2009-04-02 13:24:53 1
  • Echos the number of seconds from the current time till the specified time (Example in command is (2**31-1)) aka the Unix epoch. Just replace that number with the specified date (in seconds past Jan. 1st 1970) and it will return the seconds. NOTE: Only works in bash Show Sample Output

    echo $( (( $( (2**31 -1) ) - $(date +%s) )) )
    Chartreuse · 2009-04-02 05:14:23 2

  • 10
    while true; do X=$Y; sleep 1; Y=$(ifconfig eth0|grep RX\ bytes|awk '{ print $2 }'|cut -d : -f 2); echo "$(( Y-X )) bps"; done
    stuntdawg · 2009-03-27 08:26:39 2
  • Allows you to save progress without committing. To revert to an undo point, svn revert then apply the undo point with patch. svn revert -R . && patch -p0 < .undo/2009-03-27_08:08:11rev57 Similar: Show Sample Output

    function svnundopoint() { if [ -d .undo ]; then r=`svn info | grep Revision | cut -f 2 -d ' '` && t=`date +%F_%T` && f=${t}rev${r} && svn diff>.undo/$f && svn stat>.undo/stat_$f; else echo Missing .undo directory; fi }
    codeape · 2009-03-27 07:14:31 0
  • Allows for quick mass renaming, assuming the user has some familiarity with regular expressions. Basically, it replaces the original_file_name in the output of ls with "mv -v original_file_name new_file_name" and passes the output to sh. Show Sample Output

    ls /some/directory | sed -rn -e 's/input_file_regex/mv -v & output_file_name/p' | sh
    polar · 2009-03-25 09:20:15 4
  • Takes filenames and directory names and replace space to '_'.

    find -depth . | (while read FULLPATH; do BASENAME=`basename "${FULLPATH}"`; DIRNAME=`dirname "${FULLPATH}"`; mv "${DIRNAME}/${BASENAME}" "${DIRNAME}/${BASENAME// /_}"; done)
    mohan43u · 2009-03-24 21:04:32 6
  • The file .my.cnf located at user's home directory is used for mysql login. If this file exists, then mysql -uYOURUSERNAME -pYOURPASSWORD database -e 'SOME SQL COMMAND' can be replaced with mysql database -e 'SOME SQL COMMAND' It saves you from typing! This is valid for mysqladmin and mysqldump commands as well. Show Sample Output

    echo -e "[client]\nuser = YOURUSERNAME\npassword = YOURPASSWORD" > ~/.my.cnf
    alperyilmaz · 2009-03-24 19:05:39 3

  • 0
    vimdiff foo.c <(bzr cat -r revno:-2 foo.c)
    HorsePunchKid · 2009-03-24 18:15:48 0
  • Sometimes you want to know the summary of the sizes of directories without seeing the details in their subdirectories. Especially if it is going to just scroll off the screen. This one liner summarizes the disk usage of any number of directories in a directory without giving all the details of whats happening underneath. Show Sample Output

    for dir in $(ls); do du -sk ${dir}; done
    morlockhq_ · 2009-03-24 13:42:55 7
  • explanation: grep -- displays process ids -v -- negates the matching, displays all but what is specified in the other options -u -- specifies the user to display, or in this case negate The process loops through all PIDs that are found by pgrep, then orders a forced kill to the processes in numerical order, effectively killing the parent processes first including the shells in use which will force the users to logout. Tested on Slackware Linux 12.2 and Slackware-current

    for i in $(pgrep -v -u root);do kill -9 $i;done
    lostnhell · 2009-03-24 02:54:52 2
  • Example: To store the function addfunction after you have defined it: addfunction addfunction

    addfunction () { declare -f $1 >> ~/.bashrc ; }
    dagh · 2009-03-23 12:55:04 4
  • If you want to operate on a set of items in Bash, and at least one of them contains spaces, the `for` loop isn't going to work the way you might expect. For example, if the current dir has two files, named "file" and "file 2", this would loop 3 times (once each for "file", "file", and "2"): for ITEM in `ls`; do echo "$ITEM"; done Instead, use a while loop with `read`: ls | while read ITEM; do echo "$ITEM"; done Show Sample Output

    ls | while read ITEM; do echo "$ITEM"; done
    fletch · 2009-03-22 23:33:13 4
  • After a command is run in bash, !$ is set to the last (space-delimited) argument of the command. Great for running several commands against the same file in a row.

    svn status app/models/foo.rb; svn commit -m "Changed file" !$
    ggoodale · 2009-03-22 23:14:06 0
  • The brace expansion also allows you to count backward: for i in {15..1}; do echo $i; done You can also use this construct to create new file or new directory: mkdir dir{1..3} # Same as mkdir dir1 dir2 dir3

    for i in {1..15}; do echo $i; done
    haivu · 2009-03-21 23:08:41 1
  • If you would like to edit a previous command, which might be long and complicated, you can use the fc (I think it stands for fix command). Invoke fc alone will edit the last command using the default editor (specified by $FCEDIT, $EDITOR, or emacs, in that order). After you make the changes in the editor, save and exit to execute that command. The fc command is more flexible than what I have described. Please 'man bash' for more information.

    fc [history-number]
    haivu · 2009-03-20 15:09:43 6
  • CDPATH tells the cd command to look in this colon-separated list of directories for your destination. My preferred order are 1) the current directory, specified by the empty string between the = and the first colon, 2) the parent directory (so that I can cd lib instead of cd ../lib), 3) my home directory, and 4) my ~/projects directory.

    haivu · 2009-03-20 14:50:25 8
  • Alias two dots to move to parent directory. Put it into your .bashrc or .profile file. Show Sample Output

    alias ..='cd ..'
    eimantas · 2009-03-20 09:57:28 3
  • The output of "echo $PATH" is hard to read, this is much easier. The parentheses ensure that the change to the input field separator (IFS) only happens the the sub shell and not affecting the current shell. Show Sample Output

    ( IFS=:; for p in $PATH; do echo $p; done )
    haivu · 2009-03-19 22:45:47 3
  • You're running a script, command, whatever.. You don't expect it to take long, now 5pm has rolled around and you're ready to go home... Wait, it's still running... You forgot to nohup it before running it... Suspend it, send it to the background, then disown it... The ouput wont go anywhere, but at least the command will still run... Show Sample Output

    ^Z $bg $disown
    fall0ut · 2009-03-17 21:52:52 13
  • Hold ctrl and press z to pause the current thread. Run fg to resume it.

    mallegonian · 2009-03-16 20:58:31 4

  • 3
    sort file1.txt | uniq > file2.txt
    rain · 2009-03-14 20:24:06 6
  • NOT MINE! Taken from blog. It creates a tree-style output of all the (sub)folders and (sub)files from the current folder and down(deeper) Quoting some of hackzine's words "Murphy Mac sent us a link to a handy find/sed command that simulates the DOS tree command that you might be missing on your Mac or Linux box. [..split...] Like most things I've seen sed do, it does quite a bit in a single line of code and is completely impossible to read. Sure it's just a couple of substitutions, but like a jack in the box, it remains a surprise every time I run it." Show Sample Output

    find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
    JesusSuperstar · 2009-03-12 22:25:26 4
  • Replace (as opposed to insert) hex opcodes, data, breakpoints, etc. without opening a hex editor. HEXBYTES contains the hex you want to inject in ascii form (e.g. 31c0) OFFSET is the hex offset (e.g. 49cf) into the binary FILE

    echo -n $HEXBYTES | xxd -r -p | dd of=$FILE seek=$((0x$OFFSET)) bs=1 conv=notrunc
    zombiedeity · 2009-03-11 17:02:24 0
  • I put that line in my .bash_profile (OS X) and .bashrc (Linux). Here is a summary of what the \char means: n=new line, u=user name, h=host, !=history number, w=current work directory The \[\e[32m\] sequence set the text to bright green and \[\e[0m\] returns to normal color. For more information on what you can set in your bash prompt, google 'bash prompt'

    export PS1='\n[\u@\h \! \w]\n\[\e[32m\]$ \[\e[0m\]'
    haivu · 2009-03-09 15:34:22 0
  • This is the result of a several week venture without X. I found myself totally happy without X (and by extension without flash) and was able to do just about anything but watch YouTube videos... so this a the solution I came up with for that. I am sure this can be done better but this does indeed work... and tends to work far better than YouTube's ghetto proprietary flash player ;-) Replace $i with any YouTube ID you want and this will scrape the site for the _real_ URL to the full quality .FLV file on Youtube's server and will then will hand that over to mplayer (or vlc or whatever you want) to be streamed. In some browsers you can replace $i with just a % or put this in a shell script so all YouTube IDs can be handed directly off to your media player of choice for true streaming without the need for Flash or a downloader like clive. (I do however fully recommend clive if you wish to archive videos instead of streaming them) If any interest is shown I would be more than happy to provide similar commands for other sites. Most streaming flash players use similar logic to YouTube. Edit: 05/03/2011 - Updated line to work with current YouTube. It could be a lot prettier but I will probably follow up with another update when I figure out how to get rid of that pesky Grep. Sed should take that syntax... but it doesn't. Original (no longer working) command: mplayer -fs $(echo "$(curl -s $youtube_url | sed -n "/watch_fullscreen/s;.*\(video_id.\+\)&title.*;\1;p")") Show Sample Output

    i="8uyxVmdaJ-w";mplayer -fs $(curl -s "$i" | echo -e $(sed 's/%/\\x/g;s/.*\(v[0-9]\.lscache.*\)/http:\/\/\1/g') | grep -oP '^[^|,]*')
    lrvick · 2009-03-09 03:57:44 15
  • ‹ First  < 28 29 30 31 > 

What's this? 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

Get free RAM in %

copy/mkdir and automatically create parent directories
The --parents option will cause cp or mkdir to automatically create the parent directory structure. $mkdir --parents /one/two/three/dir will create /one, /one/two, and /one/two/three as needed before creating dir. cp will copy files with their full directory structure into the target directory with this option. Thanks to Peter Leung at: which has good examples of usage.

Replace Solaris vmstat numbers with human readable format
% cat ph-vmstat.awk # Return human readable numbers function hrnum(a) { b = a ; if (a > 1000000) { b = sprintf("%2.2fM", a/1000000) ; } else if (a > 1000) { b = sprintf("%2.2fK", a/1000) ; } return(b) ; } # Return human readable storage function hrstorage(a) { b = a ; if (a > 1024000) { b = sprintf("%2.2fG", a/1024/1024) ; } else if (a > 1024) { b = sprintf("%2.2fM", a/1024) ; } return(b) ; } OFS=" " ; $1 !~ /[0-9].*/ {print} $1 ~ /[0-9].*/ { $4 = hrstorage($4) ; $5 = hrstorage($5) ; $9 = hrnum($9) ; $10 = hrnum($10) ; $17 = hrnum($17) ; $18 = hrnum($18) ; $19 = hrnum($19) ; print ; }

Rename files in batch

Get list of servers with a specific port open
Change the -p argument for the port number. See "man nmap" for different ways to specify address ranges.

Join a folder full of split files
If you use newsgroups then you'll have come across split files before. Joining together a whole batch of them can be a pain so this will do the whole folder in one.

Inverted cowsay
It's quite fun to invert text using "" (ref: ). Slightly more challenging is to flip a whole "cowsay". :-)

list files recursively by size

Convert .wma files to .ogg with ffmpeg

Search for packages, ranked by popularity
This will take the packages matching a given `apt-cache search` query (a collection of AND'd words or regexps) and tell you how popular they are. This is particularly nice for those times you have to figure out which solution to use for e.g. a PDF reader or a VNC client. Substitute "" for "" if you want this to use Ubuntu's data instead. Everything else will work perfectly.

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.


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: