noizZze

Split and Default... With Bash and TextMate

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:

1
2
3
4
5
6
if [ -z $1 ]
then
  MY_PATH=/usr/local
else
  MY_PATH=$1
fi

And here’s how you do it geeky Bash-style:

1
2
DEFAULT_PATH=/usr/local
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.

1
2
3
4
5
6
7
8
VALUE=abcd
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:

1
${TM_SELECTED_TEXT:-$TM_CURRENT_WORD}

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:

1
${TM_SELECTED_TEXT:-$TM_CURRENT_LINE}

Amazingly simple and ultimately useful!