Thursday, December 23, 2010

Beginner Bash: Must-Know Bash Commands

I switched full time to Ubuntu Linux last year and haven’t looked back. In this year I’ve learned to love the Bash shell (which includes the Terminal in Mac and Cygwin on Windows). At this point, I can finally say I’m faster in Bash then I was in Windows Explorer, Commander, Nautilus, or the Windows command prompt; and I prided myself on being a guy with a lot of .bat files. My goal now is to write some tips I learned in the last year. Before explaining the more advanced stuff I want to introduce some of the most basic basics.
So here it is: "Stuff I wish someone had explained clearly to me a year ago". Almost all these apply to Cygwin in Windows as well as Mac/Ubuntu Terminal.

1. More than just ls – "ls" lists files. But you’ll be faster if you learn the options and parameters.

ls -l

Lists files in long format, sort of like the default on Windows. Some systems have the "ll" command mapped to this by default. If "ll" does not work for you then open up your .bash_profile file and copy this into the last line: alias ll="ls -l". That’ll map ll for you.

ls -CF –color

Adds color to your directory listing. Executables, directories, and files are all listed in different colors. Yes, this is way to hard to type and remember every time. So make an alias which forces ls to be colorized. Again, open .bash_profile and stick this in there: alias ls="ls -CF –color". Now all usages of ls get colored.

ls -a

By default, ls ignores file starting with a dot (.). The -a option lists these files.

2. More than just find

find . -name

ls does not search subdirectories by default, which the "dir" Windows command did. It takes a while to get used to is, but " find . -name "*file*" " is the same as " dir /s *file* ". It searches all directories for a given file. The period (.) must be escaped to "\.". So to search for MyClass.java do "find . -name MyClass\.java ". Yeah, the quotes are a hassle.

find -exec

You can execute a command for each result in the find result set, just use the -exec option along with some crazy notation. For instance, to open all matching files in gedit: " find . -name "*sh" -exec gedit {} \; " Again, kinda crazy syntax.

Pipe and XARGS

It’s a basic recipe to know. Here’s how to search all the files in your current directory for the word "mystring": find . | XARGS grep mystring . That’s all the grep I’ve ever needed.

Read more: canoo