Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!

Quickly eject all disks from the command line UNIX
Instead of using the following to eject all disks:
osascript -e 'tell "Finder" to eject (every disk)' 
I've found that this is much faster:
find /Volumes -maxdepth 1 -not -user root -print0 | xargs -0 diskutil eject 
Run this command from Terminal, or in a shell script, to eject all your local disks.

To eject network volumes, this code works:
find /Volumes -maxdepth 1 -not -user root -print0 | xargs -0 umount 
[kirkmc adds: The problem with this hint is that each line of code works for different types of volumes. If you have both local and network volumes, you need to use both; you could, of course, stick them together with a semi-colon separating them so they are, in effect, a single command.. In my tests, it's not really faster than the osascript code above, but I'm posting it because some may find it useful. If you have different results in speed or efficacy, please post in the comments.]
  Post a comment  •  Comments (2)  
  • Currently 1.80 / 5
  You rated: 1 / 5 (5 votes cast)
[8,383 views]  View Printable Version
Send Terminal output to iCloud UNIX
Imagine that you run a script automatically on your Mac, and that you want to check the result of that script. There are many ways you could do this, such as remotely connecting to the Mac, or sending the results by e-mail. But with iCloud, you can also save the output to a file and put it on iCloud, where you can access it with your favorite iCloud-compatible text editor on another Mac, or on an iOS device.

To do so, simply send the output of the script to a file like this:

~/Library/Mobile\ Documents/com\~apple\~TextEdit/Documents/filename.txt

So, to save a list of a directory's contents, you'd use this:

ls -al > ~/Library/Mobile\ Documents/com\~apple\~TextEdit/Documents/list.txt

That saves a file called list.txt in TextEdit's Documents folder. Look inside the ~/Library/Mobile\ Documents folder for the paths to other apps you have that can use iCloud. Each folder in the Mobile Documents folder has a Documents sub-folder. Depending on the app, you may be able to access the files on another Mac or on iOS.
  Post a comment  •  Comments (4)  
  • Currently 2.80 / 5
  You rated: 2 / 5 (5 votes cast)
[4,500 views]  View Printable Version
Command-drag to Terminal to change directory UNIX
If you hold down the Command key while dragging an icon to a Terminal window, it will cd to either the directory you dragged (if it's a folder) or the directory containing the item you dragged (if it's a file).

I don't know when this feature appeared; it might not be specific to 10.8, but that's where I discovered it.

[kirkmc adds: This is a really neat feature. Also, if you Command-drag an application or other bundle, Terminal will cd to inside that bundle. This is great if you need to access files within an application bundle, for example. The comments are saying that this is indeed 10.8 only.]
  Post a comment  •  Comments (14)  
  • Currently 4.00 / 5
  You rated: 5 / 5 (16 votes cast)
[15,027 views]  View Printable Version
Script to delete huge sparsebundle images UNIX
I needed to restart a backup for one of my Macs, which had an 800 GB disk image on my Time Capsule. It turned out to be impossible to delete the disk image - in Finder, it would just not move to the Trash, even after waiting for several hours.

I was looking for advice and most of the suggestions involved reformatting the Time Capsule, but I couldn't do this, as I had other Macs being backed up there.

I looked for a way to do this from the command line. The Time Machine disk image - a sparsebundle, a special type of disk image that can increase in size as needed - is actually a package, which has "bands" inside, many smaller files that are named hexadecimally. In this case, there were thousands of them. So many, that even deleting them from the command line didn't work - commands like rm find limitations in the lengths of lists parsed by recursion or wildcards, so a basic command like rm -f didn't work.

I ended up writing a little script, which removes the files one by one. The biggest trick here is actually the %x switch which changes $i into a hexadecimal number.

You can then either copy and save something like this as a shell script:

for i in {0..1000000}
rm -rv /Volumes/Your Network\ Disk/Your\ Mac.sparsebundle/bands/$(printf "%x" $i)

where you replace Your\ Network\ Disk and Your\ Mac with your details.

Or, you can copy and paste this line into Terminal:
for i in {0..1000000}; do rm -rv
then add a space, then drag and drop the disk image, and then (you might need to remove one space this time) add:

/bands/$(printf "%x" $i); done

Then just watch the bands being deleted, and when the script starts deleting non-existing bands, just kill it with ctrl-X.

With no bands, the sparsebundle gets deleted immediately.

[kirkmc adds: I haven't tested this. My first thought was that this seemed like overkill, but corresponding with the submitter made me realize the extent of the problem. Here is some more information on this limitation.]
  Post a comment  •  Comments (21)  
  • Currently 2.80 / 5
  You rated: 1 / 5 (10 votes cast)
[17,031 views]  View Printable Version
Save all of your Terminal activity to a file UNIX
I use Terminal everyday, and I find it a good idea to log everything I you. It makes it much easier to undo your mistakes when you know what those mistakes were. Here's how I do this:

Open Terminal's preferences.

Go to Settings, then Shell. You can choose here to run a command at startup. You could create a simple log of your session using the following:
/usr/bin/script ~/Desktop/Terminal.log
This will log everything you do and append it to the log file.

I like to keep my history so instead I wrote this small script that archives previous sessions by renaming the file with a date/time string. I then set to run at startup the following command:
Here's the script:
# Log everything you do in Terminal.

#* Formatted date & time string.
FORMATTED_DATE=`/bin/date "+%Y-%m-%d%H%M%S"`

#* Archive the previous file
/bin/cp -f ~/Desktop/Terminal.log{,.$FORMATTED_DATE.txt}

#* Begin a new one
/usr/bin/script ~/Desktop/Terminal.log
[kirkmc adds: This is a good idea. I don't use Terminal a lot, but I find that I sometimes need to remember a command I ran in the past which is no longer in my history.

Also, this is similar to something I do with texts I write. I do most of my writing in BBEdit, and I have a number of "scratch" files which I change every year. For example, I have one file for most of what I write, another just for Mac OS X Hints, and another for a specific client I write for. I archive these files at the end of the year, and create new ones. If I ever need to go back to these files to look for something I can do so. I don't bother to enter dates - which I could do easily enough with a TypeIt4Me shortcut - but if I'm looking for something I'll generally know what text to search for.]
  Post a comment  •  Comments (9)  
  • Currently 3.44 / 5
  You rated: 4 / 5 (9 votes cast)
[24,662 views]  View Printable Version
Automatically restart network on lost connection UNIX
Often times, for whatever reason, the Internet connection on my Mac will lock up. Only restarting the Airport or Ethernet interfaces seem to resolve the issue in a timely manner. (This is different from a router crash which requires a manual restart of the router - in my case an Airport Extreme.) I have developed some interconnected scripts that will automatically accomplish this task for me when attached to launchctl. This is important for me because I often have to access files over the internet and if the connection has locked up there is no way for me to access them without manual intervention.

The first script gets the active network interface. This is called by the second script which determines whether to run a matched script for either the Ethernet or AirPort interfaces. These third and fourth scripts restart either the Ethernet or AirPort connection respectively. These last two scripts can also be configured to send you an e-mail if this happens by altering the 'tobenotified" string to reflect your e-mail address in each of them. Be sure to maintain the single quotes. Or, if you do not wish to receive e-mail, comment these parts out.

Name the first script "", and the second "". This second script is what controls the rest. Attach it to lauchctl to do this automatically and never worry about a lost connection. The third and fourth scripts should be called "" and "". Of course you can always name these whatever you want, but be sure to put the path to them in the scripts. Make sure to chmod all the files executable; and, unless the scripts are altered, they should also be run from the same folder.

In order for ifconfig to run with out intervention, the script needs to be run as root. Alternatively, you could make an exception for ifconfig in your /etc/sudoers file by adding the line (if you run as admin - else put %users):
%admin    ALL= NOPASSWD: /sbin/ifconfig
I don't think this is too much of a security issue.

With this setup, I find I am nearly impervious to lost connections.
read more (397 words)   Post a comment  •  Comments (23)  
  • Currently 2.00 / 5
  You rated: 2 / 5 (6 votes cast)
[13,556 views]  View Printable Version
Automatically reclaim memory from leaky programs UNIX
Sometimes applications have a nasty habit of claiming a lot of memory and never releasing it back to the system. Over time, this can cause affect performance. Most of the time, this can simply be fixed by quitting and restarting the offending program, but I wanted to find a more elegant solution.

After searching the Internet, I found few scripts that I could tweak to achieve what I wanted. Heres what I came up with. The first script is a python script I found at StackExchange by user drfrogsplat that gets information about system memory. The second is a bash script I wrote that runs the purge command if you have over a certain amount of inactive memory, in my case 500MB (probably overkill). Note that I think you need developer tools installed to use the purge command. There's probably an easier way to do this with vm_stat directly but I'm not good enough at awk/grep/sed to it figure out.

The bash script can be attached to a launchd plist to run automatically at certain intervals or whenever you want. I seems to work pretty well for me.

import subprocess
import re

# Get process info
ps = subprocess.Popen(['ps', '-caxm', '-orss,comm'], stdout=subprocess.PIPE).communicate()[0]
vm = subprocess.Popen(['vm_stat'], stdout=subprocess.PIPE).communicate()[0]

# Iterate processes
processLines = ps.split('\n')
sep = re.compile('[\s]+')
rssTotal = 0 # kB
for row in range(1,len(processLines)):
   rowText = processLines[row].strip()
   rowElements = sep.split(rowText)
       rss = float(rowElements[0]) * 1024
       rss = 0 # ignore...
   rssTotal += rss

# Process vm_stat
vmLines = vm.split('\n')
sep = re.compile(':[\s]+')
vmStats = {}
for row in range(1,len(vmLines)-2):
   rowText = vmLines[row].strip()
   rowElements = sep.split(rowText)
   vmStats[(rowElements[0])] = int(rowElements[1].strip('\.')) * 4096

print 'Wired Memory:\t\t%d MB' % ( vmStats["Pages wired down"]/1024/1024 )
print 'Active Memory:\t\t%d MB' % ( vmStats["Pages active"]/1024/1024 )
print 'Inactive Memory:\t%d MB' % ( vmStats["Pages inactive"]/1024/1024 )
print 'Free Memory:\t\t%d MB' % ( vmStats["Pages free"]/1024/1024 )
print 'Real Mem Total (ps):\t%.3f MB' % ( rssTotal/1024/1024 )



MM=`/Path/to/python/ | awk '/Inactive/ {print $3}'`

echo "Testing status of inactive free memory..."

if [ "$MM" -gt "500" ]; then
    echo "You have too much inactive free memory." $MM"MB Releasing now..."
    exit 0
    echo "Memory ammount" $MM"MB does not meet purge threshold."
    exit 0
[kirkmc adds: I'm guessing that this will be controversial. There seem to be dozens of apps on the Mac App Store that free up memory, and I'm not convinced that this is necessary. The only time I would see this as being essential is if that inactive memory is leading to more paging. Lately, I've been amazed at how little paging my Mac mini does; with 8 GB RAM, it rarely uses more than one swap file, and this with an uptime of several days.

I think that, in most cases, if you encounter an issue with memory, it's just as simple to use the purge command in Terminal. And, yes, I do see certain applications and processes taking up a lot of memory, notably iTunes and WebProcess. But note that the purge command doesn't free up all inactive memory anyway.

And, can someone confirm that Xcode is needed to have the purge command? Mine is in /usr/bin, and I don't think Xcode installs anything there, at least any more, now that it gets put in /Applications.]
  Post a comment  •  Comments (36)  
  • Currently 1.80 / 5
  You rated: 4 / 5 (10 votes cast)
[27,687 views]  View Printable Version
Getting and setting printer options from the command line for use with lpadmin UNIX
lpadmin and lpoptions don't interact with OS X as you might think, or at least as they are documented. Here are some helpful notes and a script.
There are some good hints for adding printers via the command line with lpadmin: Managing multiple printers via the command line.
However, there is still confusion surrounding the setting of printer options from the command line, as a poster to Debian bugs pointed out back in 2006: lpoptions documentation doesn't. After doing some testing, here are the two main points to note:

  • If you use lpadmin and specify options with "-o", the PPD is altered and OS X will recognize the options for the printer.
  • However, if you setup the printer using lpadmin without any options, and later use lptoptions to set the options, they are not written to the PPD and the GUI is unaware of the printer's options.

    More helpful hints about lpadmin and lpoptions:
    lpoptions -p printername -l
  • Prints PPD options, "Default" is filtered from option name (similar to looking at the raw PPD)
  • It uses a colon when reporting key value pairs; replace that with an equals sign when specifying an option
  • The option name stops at the first slash
  • Example: The duplex option for HP printers will output like this "HPOption_Duplexer/Duplex Unit: *True False"
    When specified as a "-o" option it would be "HPOption_Duplexer=True"

  • lpadmin ... -o this=that
  • Alters the ppd that is placed in /etc/cups/ppd/ when the printer is installed

    Unhelpful things:
    lpoptions -p printername
  • These are NOT the PPD options you want to set

    lpoptions -o
  • This only writes options to: /private/etc/cups/lpoptions (run with sudo) or ~/.cups/lpoptions (run as current user), GUI apps are unaware of these options

  • read more (470 words)   Post a comment  •  Comments (7)  
    • Currently 4.00 / 5
      You rated: 5 / 5 (7 votes cast)
    [12,226 views]  View Printable Version
    10.7: Fix crash when running shell scripts from script menu UNIX
    It seems that 10.7 no longer wants to run shell scripts from the script menu. This may also happen in 10.6, but I do not have an install to test it with.

    No matter what script I try, the SystemUIServer crashes. And somewhere in the crash report is this ominous message:


    This might have something to do with Apple tightening privileges for spawning processes, but it can be easily fixed by enclosing the shell script in AppleScript.
    do shell script "sh ~/"
    [kirkmc adds: I haven't tested this; I don't run shell scripts from the script menu, so I haven't seen crashes.]
      Post a comment  •  Comments (8)  
    • Currently 2.40 / 5
      You rated: 4 / 5 (10 votes cast)
    [3,744 views]  View Printable Version
    Control+T in Terminal shows time snapshot UNIX
    Not sure if this was available before 10.7, but hitting Control+T while running a command in the Terminal will show what process is executing, the load, the PID of the process and its user and kernel time.

    I was running a script and accidentally hit Control+T instead of Command+T to create a new tab. I was surprised at what I got. Here is an example of what gets printed:
    load: 2.51  cmd: p4 15179 running 0.00u 0.00s
    load: 2.23  cmd: p4 17962 waiting 0.01u 0.00s
    load: 2.53  cmd: Python 15167 running 94.68u 66.33s
    load: 2.60  cmd: Python 15167 running 150.71u 101.82s

    [crarko adds: I wasn't able to reproduce this, but it may be due to the briefness of the running command. Give it a try and post a comment about your results. Try it in Snow Leopard too if you can.]
      Post a comment  •  Comments (22)  
    • Currently 3.89 / 5
      You rated: 1 / 5 (9 votes cast)
    [13,657 views]  View Printable Version