views:

2377

answers:

50

bash, bat, whatever...

What is your favourite command line hyperproductivity trick?

+14  A: 

Running grep over directories with code, often with find (and sometimes xargs when needed). For me this is typically faster than using the equivalent tools in an IDE, although I guess that mostly shows my age.

unwind
Has nothing to do with age. find + grep is the ultimate tool.
troelskn
http://betterthangrep.com/
Martin Carpenter
In my project grep takes "ages". Cscope works much faster.
Mykola Golubyev
@Martin: +1: ack is the best command-line code-searching tool ...
Joachim Sauer
That probably just means that you haven't put in the effort to learn your IDE.
JesperE
grep "IP" -r *.log
Rodrigo
You should look into cscope or mlcscope. But if you must stick with `grep`, you should try `git grep`, it's much nicer (and usually eliminates the need for `find`).On a side note, 34? Age? Now you're making *me* feel old.
Dan Moulding
+28  A: 

Ctrl-R in bash to search for a previously entered command.

ammoQ
also note if you go back too far you can Ctrl-N to go back the other way.
chillitom
A: 

I like my bash prompt to be a different colour. In your .bashrc or .profile:

PS1='\033[01;34m\n[\[email protected]\H \W]$\033[00m '
anon
+42  A: 

Entering

START .

to open a Windows Explorer window for the current directory.

Dave Webb
Never come across this before... useful :D Especially with the explorer extension to open a command line window in a directory from the context menu :)
workmad3
Cool ... i didn't know that :)
n00ki3
I use %CD% instead of '.'. The same $cd in nix bash
abatishchev
Equivalent in OS X: `open .` (there are a bunch of using flags, the one I used most is `open -a "TextMate"`. Or to combine the two: `open -a "TextMate" afile.txt`), and in Gnome `gnome-open .`
dbr
Using %CD won't work for directories with spaces in them such as "Program Files". Using "%CD%" won't work either thanks to one of the peculiarities of the START command; this will open another command prompt window rather than an Explorer window as anything in quotes is taken to be Window title.
Dave Webb
Wow!! thats neat and new to me :)
Shoban
Cool. Do you know how to do the opposite (opening a command prompt in a directory you're looking at from Windows Explorer) ?
Yann Semet
i used to type explorer .
Nils
"explorer ." will do the same thing. "start" is actually for something else.
ldigas
START is for opening files with their default application and the default application for a folder is Windows Explorer, which is why it works. It's three fewer keystrokes to type START than EXPLORER which is why I do it that way.
Dave Webb
Yep, this would be mine too. I was very happy to discover 'open .' on my new MacBook.
Cannonade
As for the reverse - open a Command Prompt for a directory from Explorer - Google for "Command Prompt Here"
Dave Webb
Equivalent in most Linux distributions:xdg-open .
seanhodges
@Dav Webb: Using `start "" "%CD%"` will work. `start .` is much easier, but the other format can be useful for use with other environment variables.
Hosam Aly
or "explorer ."
RobS
Not to mention the fact that explorer is a specific app, "start <path>" will use the registered file manager - which can be something else than explorer, really... ^^
Oskar Duveborn
How ironic that the best Windows command line trick is a way to escape the command line??!
chillitom
chillitom: Integrating shell and unshell environments is important. Directory -> Open in Terminal etc. You see?
kaizer.se
+6  A: 

Pipes in general. Imagine you want to find out how many files that have a particular string in their filename are in a folder. You could do it like this:

ls -l | grep yourstring | wc -l
# Sample output: 52
Lennart
or even better: ls *yourstring* |wc -l
Nathan Fellman
@Nathan Fellman, That's a bit different ... That could look through directories (e.g. if 'yourstring' was source). Also, it doesn't support the better regexp features (only globbing).
strager
Better: "ls | grep -c yourstring" :)
Porges
porges you read my mind i was going to post the same, grep -c counts instances so no need for wc.
John T
A: 

scripts and IF.

kenny
+17  A: 

Favourite command line hyperproductivity trick:

I like the Tab key for path/file completion in bash.


Favourite command line tool:

man [command]
Peter
Nice use of the <kbd> tag.
spoulson
You can also set bash to ignore case for the completion. Put `set completion-ignore-case On` in ~/.inputrc
Marko
Works on Windows command line also!
Jon
+1  A: 

Piping the output of grep (or findstr) to itself to exclude things I don't want. For example:

findstr /spin /c:"foo" *.cc | findstr /v /c:".svn"
jeffamaphone
+6  A: 

Turning on tab completion in a Windows command shell.

set \HKCU\Software\Microsoft\Command Processor\CompletionChar to 9

After that use tab to auto-complete filenames in shells.

I think Vista has this turned on by default but XP doesn't

Fortyrunner
+1: Finding this made working ind cmd.exe bearable for me
Joachim Sauer
Hmmm... I used to find this enabled by default on Windows XP. I never knew that it can be enabled or disabled, but I've always used it.
Hosam Aly
I think they enabled this by default in some servicepack. I distinctly remember having to enable it manually (and having to look up the correct registry key and value each time) on multiple Windows XP machines.
Joachim Sauer
+3  A: 

At the Mac OS X bash prompt issuing

open Filename

starts up the application associated with Filename and loads the file.

RobS
Windows equivalent: start Filename Unix equivalent: xdg-open Filename
Jörg W Mittag
Thanks for the Unix equivalent, I've been looking for that for ages.
RobS
To be precise: it's not Unix, it's XDG (Free Desktop). KDE, Gnome, Xfce and others are XDG-compliant, but some more obscure ones are not, and of course it only applies to graphical desktop environments, not necessary commandline-only systems.
Jörg W Mittag
The fish shell can do that too ^^
Helper Method
+26  A: 

I think you are looking for the Command-line Fu Website! :)

Node
Great thanks for the link!
Masi
Have found some cool things on that site, yes :D
Svish
A: 

In tcsh, using CTRL-X+? to expand paths and aliases, CTRL-X+$ to expand variables and CTRL-X+* to expand globs.

Some examples:

> alias l less
> l
# press CTRL-X+?
> less
> set l less
> $l
# press CTRL-X+$
> less
> ls
a.c b.c c.h
> echo *.c
# press CTRL-X+*
> echo a.c b.c
Nathan Fellman
+5  A: 

In bash:

set -o vi

turns on vi mode. Also, adding this to ~/.inputrc will turn on vi mode for anything using readline:

set editing-mode vi
set keymap vi

I am more familiar with the vi commands than I am with the emacs ones, so these changes give me a productivity boost.

gpojd
+13  A: 

Insert preceding line's final parameter (bash)

Alt-. is one of the most useful key combinations; for some reason no one knows about this one. Just try it and see

Press it again and again to select older previous parameters.

Great when you want to do something else to something you used just a moment ago, try it and see.

Update Example

Let's say you have the following files in a directory:

06.Jimmies_Joys-Wolverine_Blues.flac
06.King_Oliver-Jazzin_Babies_Blues.flac
07.Cotton_Pickers-You_Tell_Her,_I_stutter.flac
07.Mammie_Smith-Lady_Luck_Blues.flac
08.Paul_Whiteman-If_I_Cant_Have_The_Sweetie.flac
08.The_Georgians-Loose_Foot.flac
09.Jelly_Roll_Morton-Wolverine_Blues.flac
09.Wades_Moulin_Rouge_Orchestra-Mobile_Blues.flac

Sadly, you didn't notice that the CDDB entry for CD6 was mislabeled CD5, and so all the entries for CD5 and CD6 are now mixed. You take out the liner notes and want to move the true CD6 music up a level and into the appropriate subdirectory because OCD compels you so. Here's what you do:

  1. cd *CD5*
  2. mv 06.Jtab ../*CD6*
  3. mv 07.Mtab Alt-.

Using Alt-. will auto-complete ../*CD6* FTW.

chillitom
yes.. I didn't know this one
Nils
weird, why would you need this?
Can you give an example? I am unable to use it correctly.
Masi
use it when performing two operations on the same file/argument.. saves a lot of typing.for example: # ls readme.txt <enter> rm <alt-.>
chillitom
Press up arrow does the same thing.
Hai
It's not the same as the up arrow. Try entering: `grep "foo" *` and then pressing it three times. You get just `*` then just `"foo"` then just `grep`. This seems to traverse the history token-by-token instead of line-by-line (like up arrow).
Tyler McHenry
+1  A: 

When trying to find if a specific program is running: ps options | grep [p]rogram

That is, turning the program name into a non-self-matching regular expression.

Vatine
or just use **pgrep**
chillitom
Oh? Is that standard on all unix versions? I prefer tricks that are portable across unixes I either touch daily or have, historically, spent a lot of time with (the list includes, but is not limited to, AIX, HP-UX, SunOS4, Solaris, Linux, xBSD, D/NIX).
Vatine
@Vatine: It is available on OpenSolaris, FreeBSD and Linux from what I have gathered, not sure about the others.
X-Istence
+3  A: 

Creating a m3u file from command:

dir /B *.mp3 > playlist.m3u
Davy Landman
+19  A: 

On Windows:

TaskList /M nameof.dll

Gives you a list of all the running processes that have the DLL loaded. This is useful if you're trying to track down a locking issue.

Sean
I am using processexplorer for this
erdogany
+2  A: 

Here's a way to show any file in Windows Explorer (open window and highlight file; at least, if the file's directory window is not already open):

explorer /select,"c:\windows\notepad.exe"

Or, if you like "explore" (show file tree) better:

explorer /E,/select,"c:\windows\notepad.exe"

(I'm just taking notepad as an example, as that path probably exists on your PC.)

Note that Explorer will crash if the path does not exist.

bart
+1  A: 

bash-completion: the greatest things since bash completion

This gives you relevant completion suggestions for what you've currently typed. Extremely useful!

Ryan Fox
+4  A: 

On Windows:

explorer /e,/root, path

Will launch an explorer instance with the root set to path. This is handy when you're browsing source code and just want an explorer view from the root of the code down.

NOTE: The strange commas are correct and there needs to be a space after the last comma and before the path.

Sean
+4  A: 

I use alt-f/b in bash to jump over words along with ctrl-a/e to navigate to the end/beginning of the line. Ctrl-u deletes everything left from the cursor, ctrl-k everything right from the cursor.

On Windows you can use ctrl-left/right. Home/End, however I haven't found a shortcut to delete everything left/right from the cursor.

Nils
+6  A: 

In Bash, the ! keyword thingummy.

e.g.

!ssh

runs the latest entry from your command line history that began with 'ssh'.

or

!224

reruns entry #224 from your history.

Useful when you have to run the same command several times, for example, running ssh with loads of command-line options specified.

ZombieSheep
Personally, I hate this, and use "set +H" to disable it. With EMACS key bindings, just use Ctrl-R followed by the pattern (here, "ssh") to see (and maybe edit) the command line BEFORE it runs!
NVRAM
@NVRAM - I agree this is not the ideal solution if you need to edit the command, but for repetitive tasks (that are not worth scripting) this works for me. :)
ZombieSheep
Watch out if you're root. More than once I've run !find in order to repeat the last find command, having forgotten that it expanded out to "find . -size +1000000c | xargs -t rm -f". While benign in the originally intended directory, it wrecked havoc when I accidentally ran it in /var.
Barry Brown
+12  A: 

From a Windows XP command prompt, might be a known feature but I use it all the time. hitting the F7 key will bring up the list of previously issued commands.

SomeMiscGuy
+1 Didn't know that one...
Daniel LeCheminant
Strange, that does not work for me? Why? I'm running XP Home SP 2...
presario
this also works in windows 7 - just tried it :)
chama
Up/down arrows do similar things
Jon
+3  A: 

in bash, for loops. I particularly like the structure:

for f in *; do cd $f; for g in *; do [STUFF]; done; cd ..; done
Brian Postow
Breaks with spaces.
Porges
True, but real unix filenames shouldn't have spaces! unix breaks with spaces in general.
Brian Postow
Ehm, why should real unix file names not have spaces? What makes files without spaces more real than files with spaces?
X-Istence
yikes, why the downvotes? loops on the command line are gold!
Mr. Shiny and New
RE Spaces: because unix doesn't deal well with spaces. you can't do anything with a * when you have files with spaces. files with spaces are hard to workwith.
Brian Postow
Actually, since the shell expands the "*" properly this example works with spaces in names (an abomination on any platform!) if you surround the variables with double quotes: cd "$f" (and in "[STUFF]").
NVRAM
yes, but you need the quotes everywhere, and that's just hideous. but yeah... I'm still annoyed that ls * doesn't just work...
Brian Postow
A: 

in unix/sh, Using find in conjunction with while read in order to perform a common operation on certain files within a directory tree.

Change permissions of directories only:

find ./ -type d |while read x; do chmod go+rx "$x"; done

Remove files not accessed in more than a week:

find ./ -type f -atime +7| while readx; do rm "$x"; done

The find command allows one to ferret out those files with common characteristics, and the while read construct makes makes it simple to perform operations on each.

vezult
find has a couple of exec options that does the job ;)
Sujoy
those are nice when you only want to do something as simple as my examples. If you want to do something more complex then find by itself is pretty awkward.
vezult
+20  A: 

How to paste on windows console: alt+space+e+p

I know it's huge and complex but it saves me 50 times per day.

cherouvim
IF you go to the command window properties and turn on Quick Edit mode, copy becomes select with mouse, press enter or right-click; paste becomes right click.
benPearce
thanks benPearce. Sometimes I prefer not to touch the mouse though.
cherouvim
Sadly can't copy the screen using only the keyboard, but this is a good save-time shortcut
Rodrigo
+4  A: 
% perl -ne "print if /something/" < infile

Prints all of the lines with the regex something in them, from the file infile. "-e" tells perl to interpret the next argument as a script (&& run it), while "-n" tells perl to add a "while (<>) {}" around the whole script, which is like saying 'execute the script for every line of input'.

Great for parsing log files.

Joe
or just # grep "something" infile
chillitom
Sure, unless you're on windows and haven't bothered to download grep. And why bother? Perl not only allows me to grep, but to whatever I want if /something/ exists.
Joe
Perl's regexes are also much more advanced than grep's.
Ben Blank
+1  A: 

To cut and paste arguments to a command

cmd `cat`

paste followed by ctrl-d

Karl
A: 

On Windows, when working with code, often I do heavy use of Command Window Here and then findstr

findstr /c:"string_to_be_searched" /s *.cpp

Is pretty useful.

Alex. S.
+3  A: 
  1. grep -v (Invert match)
  2. ls -ltr (Last modified files first)
  3. cat file | sed 's/old/new/' (Replace regex old with new)
Feline abuse: should be "sed 's/old/new/' < file" instead. :-)
Ben Blank
A: 

IP range scanner

$for /L %i in (1,1,254) do @ping  192.168.1.%i -n 1 | find /i "reply" > nul
&& @echo 192.168.1.%i is alive
A: 

Print Disk Volumes

$fsutil fsinfo drives

would result an output like this Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\ Piping to more would result the following output $fsutil fsinfo drives | more

Drives: C:\ D:\ E:\ F:\ G:\ I:\ J:\

using for to get volumes would result an output like thi

$for /F "skip=2" %i in ('fsutil fsinfo drives ^| more') do @echo %i

D:\ E:\ F:\ G:\ I:\ J:\

then you can get first volume as follows

$for /F "tokens=2" %i in ('fsutil fsinfo drives') do @echo %i

would result an output like this C:\

any enhancement for this would be cool

A: 

Command line calculator to enhance batch arithmetic operations specially divison math written in C#

**class Program
    {
       static void Syntax()
        {
            System.Console.Write("Example: calc 10 + 25 or calc 10 / 2 \n");
        }

        static void Main(string[] args)
        {


            try
            {
                if (args.Length == 3 && args.Length != 0 && Microsoft.VisualBasic.Information.IsNumeric(args.GetValue(0)) && Microsoft.VisualBasic.Information.IsNumeric(args.GetValue(2)))
                {


                    //foreach (string var in args)
                    //{


                    string op = (string)args.GetValue(1);
                    double arg1 = System.Convert.ToDouble(args.GetValue(0));
                    double arg2 = System.Convert.ToDouble(args.GetValue(2));
                    switch (op)
                    {

                        case "+":


                            System.Console.Write(arg1 + arg2);

                            break;
                        case "/":
                            //double v = Convert.ToDouble(args.GetValue(2));
                            if (arg2 == 0 || arg2 == 0.0)
                                System.Console.Write("Cannot divide by zero!.");
                            else

                                System.Console.Write(arg1 / arg2);


                            break;
                        case "*":
                            System.Console.Write(arg1 * arg2);
                            break;
                        case "-":
                            System.Console.Write(arg1 - arg2);
                            break;
                        default:
                            Console.WriteLine("An attempt to an illegal operation! please check syntax.\n");
                            Syntax();
                            break;
                    }


                    //}

                }
                else
                {
                    System.Console.Write("Missing argument or bad syntax .\n");
                    Syntax();

                }
            }
            catch (Exception ex)
            {
            }

        }
    }**

then you can invoke command line compiler on it as follows %windir%\Microsoft.NET\Framework\v2.0.50727\csc.exe calc.cs

A: 

get count of lines with native windows tools such as

$find /v /c "no_where_string" filename
+1  A: 

I have too much music I guess; so here is one thing I use that hasn't been listed:

locate -i artist | grep -i mp3$

substitute artist for song name etc. I include the "-i" options to make it case in-sensitive. I had to edit /etc/updatedb.conf to include my mounts in /media

Eddy
A: 

to get ip settings networkid and hostid get ip address

for /f "tokens=15" %i in ('ipconfig ^| find /i "ip address"') do set ip=%i

get networkid

for /F  "tokens=1,2,3 delims=." %i in ('echo %ip%') do  @set ip=%i.%j.%k.
A: 

Shell-fu is a place for storing, moderating and propagating command line tips and tricks. A bit like StackOverflow, but solely for shell. You'll find plenty of answers to this question there.

Jean-Marc Liotier
A: 
wget -t0 -np -r -l0 "www.suckthiswebsite.com"
Rodrigo
A: 

For bash, using !$ to repeat last argument to last command.

ls /var/log/messages
cp !$ !$.270809

And the magic carets, although I rarely use them nowadays:

[[email protected] /] usradd -u 666 -g 10 -u guest
bash: usradd: command not found
[[email protected] /] ^ra^era^
useradd -u 666 -g 10 -u guest

Last but not least, for infinite loops I use this (not a trick, just a quirk of mine :)

until [6 -eq 9]; echo "Jimi has really gotten into me."; done
Michael Foukarakis
A: 

In bash I sometimes misuse the fact that I know globbing a pattern will result in exactly two filenames. So if i have two textfiles stuff.txt and stuff.txt.org and I want to compare there contents I enter:

diff stuff.txt*
Peter van der Heijden
A: 

Copy to clipboard (in bat) :

MyCommand | clip

Actually, I just discovered it, but I'll surely use it every day now :)

Gzorg
A: 

Grep emacs from the output of ps aux, while filter out the grep emacs command itself

ps aux | grep [e]macs
ZelluX
A: 

In Bash, I like to:

  • move up N directories quickly
  • dynamically assign directories so that I can switch between 2-3 dirs quickly, and reference them for file copying etc

for details on the alias definitions, see my blog post. It is easy stuff but very useful.

Michael Easter
+1  A: 
!!

repeat the last command. It is useful when you type, by example:

apt-get install

and forget the sudo, so:

sudo !! 

do it for you.

Hai
A: 

egrep , which basically does what ps -e | grep does ^^

Helper Method
A: 

cp file.{txt, bak} to make a backup.

Helper Method
A: 

There's an excellent website for bash command line, CommandLineFu.

My favourite under linux is:

rm -rf *

Seriously though, it has to be Ctrl+A and Ctrl E for editing on the linux command line, (Home/End) respectively. There is another one that I use when messing with bootsectors...

dd if=/dev/hda3 of=/bootsect.bin bs=512 cnt=1

As for Windows, it has to be Winkey + 'R', cmd enter. Much faster than clicking on Start, Run, cmd.

Hope this helps, Best regards, Tom.

tommieb75
A: 

Using my cutomized PS1 variable:

\[\033[3;44m\]\[email protected]\h:\W$\[\033[0m\]
Xolve
what this command does?
lsalamon
put the following at the end of the .bashrc filePS1=\[\033[3;44m\]\[email protected]\h:\W$\[\033[0m\]And open a new shell to see the effect.
Xolve
A: 

One of my faves, in windows, is the tree command

tree <dir>

//e.g.

D:\axis2-1.2\dist>tree
Folder PATH listing
Volume serial number is 0000AC08 EC5E:85B4
D:.
+---axis2-web
¦   +---css
¦   +---Error
¦   +---images
¦   +---include
+---META-INF
+---WEB-INF
    +---classes
    +---conf
    +---lib
    +---modules
    +---services

tree /f <dir>    //lists all files too - very handy

I haven't found anything quite as nice in unix, although this comes close...

//can't remember who i got these ones from, but thanks anyway
ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'

or

find . -print | sed -e 's;[^/]*/;|____;g;s;____|; |;g'
mlo55
A: 

Processing a file a line at a time.

cat filename | ( while read LINE ; do ... ; done )

You can also do tricks with IFS like

cat filename | ( while IFS=, read ONE TWO REST ; do ... ; done )
staticsan