Split and Default… with Bash and TextMate
Posted: August 2nd, 2009 | Filed under: Programming | Tags: bash, textmate, Tips | No Comments »There’s a couple of Bash patterns I often use in my scripting that I would love to share. Both of them are immediately useful in your TextMate practice through commands, and that’s what makes the study really fun.
Default Values
Assuming that you want a user to give you the path as the first argument and fall back to something if he didn’t, normally you may have done this:
then
MY_PATH=/usr/local
else
MY_PATH=$1
fi
And here’s how you do it geeky Bash-style:
MY_PATH=${1:-$DEFAULT_PATH}
Shorter and delivers the message way more transparently, doesn’t it? That minus sign before the $DEFAULT_PATH is critical, so don’t miss it. Which leads us to the next tip.
String Splitting
If you need only some part of the string, you can easily cut it out knowing the start/end indexes or just one of them.
INDEX=2
# Gives 'ab'
LEFT_FROM_INDEX=${VALUE:0:INDEX}
# Gives 'cd'
RIGHT_FROM_INDEX=${VALUE:INDEX}
What about TextMate?
Now that you possess the secret knowledge, you can use it in your TextMate commands. One example scenario mentioned all around is replicating the common pattern where the command operates either on the selection or the current word. Here’s how it would look:
Note the order of the parameters, TM_CURRENT_WORD is the default, not the other way around. If there’s nothing selected, it will come in handy. Now, if you read my previous posts on Ruby / Shell code execution, this should ring a bell. Here’s how the selection-or-line logic would look:
Amazingly simple and ultimately useful!
The Ruby on Rails addict, industrial photographer and amateur electronic music composer. In the mean time I build great web applications, contribute to OSS and help AVAAZ to save Great Barrier Reef.
Leave a Reply