In an effort of DRY I'm trying to automate my monthly workflow of downloading bank statements and then storing them in a secure Sparse Bundle.
I've created a script that uses hdiutil mount
to mount my sparsebundle and hdiutil detach
to unmount/eject the disk and image (SIDE NOTE: if you use unmount
here malicious users will be able to mount the volume without being prompted for a password).
I have the entire script working except for a spot for a potential bug. When I mount the image I use the following:
hdiutil mount -owners on -stdinpass <name of image>
add the following output results
/dev/disk1 Apple_partition_scheme
/dev/disk1s1 Apple_partiti开发者_C百科on_map
/dev/disk1s2 Apple_HFS /Volumes/Bank-Statements
Right now the script just has hdiutil detach disk1s2
hardcoded into it which is bad because that value will change if I ever have other things mounted when this is run. How do I just grab the /dev/disk1s2
? I know I can do
hdiutil mount -owners on -stdinpass <name of image> | grep "Bank" |
but after that I'm stuck. I know this can be done with Perl or Ruby but I'd like to see it solved with awk, grep, or sed as I'm not as familiar with those tools and this can be a good learning experience.
Thanks!
Sounds cool!
The most direct solution is with awk (maybe sed).
I'm dropping your "grep 'Bank'" as awk and sed can 'grep' for targets too.
hdiutil mount -owners on -stdinpass <name of image> | awk '/Bank-Statements/ { print $1}'
(given you example output above) will return
/dev/disk1s2
(unless there are spaces in front of /dev...., then change $1 to $2 )
I hope this helps.
Both OS X grep and GNU grep support Perl Compatible Regular Expressions using the -P
option:
hdiutil mount ... | grep -Po '^[^ ]+(?= .*Bank.*)'
A sed
command would be similar:
hdiutil mount ... | sed -n '/Bank/s/^\([^ ]\+\) .*/\1/p'
Either command will output all non-space characters starting at the beginning of the line on line(s) that include the word "Bank". If the hdiutil
command outputs tabs, then you can change the spaces above to [[:blank:]]
which will match either spaces or tabs. For example:
hdiutil mount ... | grep -Po '^[^[:blank:]]+(?=[[:blank:]].*Bank.*)'
or
hdiutil mount ... | sed -n '/Bank/s/^\([^[:blank:]]\+\)[[:blank:]].*/\1/p'
精彩评论