Useful for when you're setting up a new wifi-enabled RPi without an external monitor/keyboard. The best way to do this is by using a TTY to Serial Cable, per the instructions here: http://learn.adafruit.com/adafruits-raspberry-pi-lesson-5-using-a-console-cable/
Note that this only works for non-hidden networks.
sudo nano /etc/network/interfaces
For regular networks, replace whatever's in there with this:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-ssid "Network Name"
wpa-psk "password"
If you've got a hidden SSID, use this instead:
auto lo
iface lo inet loopback
iface eth0 inet dhcp
auto wlan0
allow-hotplug wlan0
iface wlan0 inet dhcp
wpa-scan-ssid 1
wpa-ap-scan 1
wpa-key-mgmt WPA-PSK
wpa-proto RSN WPA
wpa-pairwise CCMP TKIP
wpa-group CCMP TKIP
wpa-ssid "Network Name"
wpa-psk "password"
iface default inet dhcp