How to create a UNIX bash script on a mac

Leave a comment

The ability to create and make your own custom bash scripts is on of the biggest advantages to working off a unix based operating system (like the mac).

You can take just about any mundane, or complicated task, and easily automated it by learning how to create your own bash scripts.

In this post I am going to show you how to create a bash script called:

findtext.sh

(which recursively search all files for text containing xxx (very handy)) and call it from anywhere on your computer.

Setup your environment

Go to your home directory:

$ cd ~

and make a directory called scripts (this is where you will store your scripts):

$ mkdir scripts

Then if you don’t have one already, create a .bash_profile file (in your root directory) and add the following line:

export PATH=$PATH:~/scripts

This puts the directory you just created into the unix $PATH variable which lets you call your scripts from anywhere on your machine.

To register this new path you may need to go:

$ source .bash_profile

You can then check your new path by typing:

$ echo $PATH
/opt/local/bin:...:/usr/local/bin:/usr/X11/bin:/Users/jr/scripts

If all is well you should see your new directory in the output.

OK. We are now ready to create your script.

Create your script

To create your script go back to that scripts directory your just created and using your favorite text editor create a file called ‘findtext.sh’

#!/bin/bash
echo "Searching for text:" $1
find . -type f -exec grep -il $1 {} \;

And give yourself permission to execute it using the following command:

$ chmod 711 findtext.sh

That’s it! At this point you are basically done.

You should now be able to run this script from anywhere on your box.

To test it out, navigate to some directory containing a lot of files and text and search for something.

Here is the output I get when I search my rails app for ‘README’

$ findtext.sh README
Searching for text: README
./testApp/doc/README_FOR_APP
./testApp/generate/doc/README_FOR_APP
./testApp/generate/README

Enjoy.

For more information on bash and scripting click here.

Git GitHub Heroku RubyOnRails How to

Leave a comment

This is a github cheat sheet I created after going through Michael Hartl’s excellent getting start with git tutorial as part of his also excellent online RubyOnRails book.

For a more thorough walk through go here. For a quick fix read on.

Create new git repository

Assuming you’ve installed rails, git, created a github account, and have a rails app you want to put under version control, navigate to the root of your rails app and create a new git repository as follows:

$ git init

Then create an ignore file at the root (in this case using TextMate) and add the following

$ mate .gitignore

log/*.log
tmp/*
tmp/**/*
doc/api
doc/app
db/*.sqlite3
*.swp
*~
.DS_Store

Add your files to the repository recursively

$ git add .

Do your initial commit

$ git commit -m "Initial commit"

Create your new repository in github using the github UI.

Then push (save) your application to github.

$ git remote add origin git@github.com:/first_app.git
$ git push origin master

There. Your repository is setup!

Branch, edit, commit, merge

Create a new branch

$ git checkout -b myChanges

Make some changes (in this case rename a file)

$ git mv README README2

If you’ve made a mistake, roll it back.

$ git checkout -f

Commit the change to your branch

$ git commit -a -m "Moved the README file"

Merge with master branch

$ git checkout master
$ git merge myChanges

Then push to git server

$ git push

Deploy Heroku

For details on Heroku setup go here.

To create an instance of your app on Heroku and deploy go:

$ heroku create
$ git push heroku master

Then push, deploy, and view your app regularly with:

$ git push
$ git push heroku
$ heroku open

Voila! You’re done!

Filling the joy bucket

Leave a comment

Making money is great.
And when you get paid by the hour it’s tempting to work as many billable hours as you can.

But while billable work is great for the bottom line, it’s not always great for the soul.
You’ve got works of art you want to create. Start-up ideas you want to do.

But not maximizing your billable hours feel like your leaving money on the table.

So what’s does a poor boy do?

Try this.

Find out what your most productive time of day is (the hours where the creative juices are really flowing) and see if you can’t reserve 1-2 hours each day to focus on one true your passion.

Then, for one week, block off those core hours and don’t let anything keep you from doing whatever it is you need to do.
artist at work
Start that book.
Build that protoype.
Learn that guitar song.
Make that movie.
Spend that time with the family.

Whatever it is you need to do to fill your joy bucket, do it.

Do this for a week then reflect.

  • Do you feel better for having spent time on x,y,z?
  • Are you less stressed because you feel like you’ve accomplished something you’ve always wanted to do?
  • Do you look forward to getting up in the morning, knowing you’ve set time aside for something you really enjoy doing.

I’m not saying life is all fun and games, and there won’t be times you need to buckle down and get stuff done.

But by setting aside some time for those things you feel compelled to do, you can put food on the table, and enrich your life (and the lives of those around you) at the same time.

So block off that time. Give yourself a week. And see if you’re happier.

You know what’s important in your life.
Go do it.

More Watin MVC.NET examples

1 Comment

Now that we’ve got you started let’s dive a little deeper and see how to put Watin into action.

It’s all about the ids

Watin works by finding a control on your page, and then giving you access to it programmatically in your Watin unit test.

The easiest way is to let Watin get at your controls is to give each one a unique id.

For example, say we created a sample MVC.NET page that looked something like this:

For Watin to be able to access each of the controls on this page, we need to give them an id as follows:

    <input id="MyTextArea" type="text" value="A text area" /> <p/>
    <input id="MyButton" type="button" value="Push Me" /> <p/>
    <input id="MyCheckBox" type="checkbox" /> A checkbox <p/>
    <input id="MyRadioButton" type="radio" /> A radio button <p/>

    <table id="MyTable" >
     ...
    </table>

Then accessing them in a Watin simply becomes:

        [Test]
        public void HitSomeControls()
        {
            using (IE browser = new IE("http://localhost:4642/Home/WatinTestPage"))
            {
                // grab the controls
                TextField textField = browser.TextField("MyTextArea");
                Button button = browser.Button("MyButton");
                CheckBox checkBox = browser.CheckBox("MyCheckBox");
                RadioButton radioButton = browser.RadioButton("MyRadioButton");

                // make some assertions
                Assert.AreEqual("A text area", textField.Text);
                Assert.AreEqual("Push Me", button.Text);
                Assert.IsFalse(checkBox.Checked);
                Assert.IsFalse(radioButton.Checked);
            }
        }

Now tables are exactly the same. They just require a little more work.

        [Test]
        public void ParseTheTable()
        {
            using (IE browser = new IE("http://localhost:4642/Home/WatinTestPage"))
            {
                // get the first row of table data
                Table table = browser.Table("MyTable");
                TableRowCollection tableRows = table.TableRows;
                TableRow row = tableRows[1];
                ElementCollection rowData = row.Elements;

                string name = rowData[0].OuterText;
                string phoneNumber = rowData[1].OuterText;

                Assert.AreEqual("Paul", name);
                Assert.AreEqual("403 111 1111", phoneNumber);
            }
        }

* If you want the browser window to stay up after running the test remove the using statement (that will stop it from closing)

You could access any row or element of the table too. All you’d have to do is create an id for each row, and assign it a user id when you generate your table (probably in a foreach loop).

The Page abstraction

Now we could leave our tests as is, but chances are you are going to be writing a lot of them so anything we can do to make them more maintainable will help.

To keep all the unique id’s in one page, and make the tests a little more readable, I’ve found it handy to create a Page class for the MVC.NET view I am testing, and put all the Watin specific stuff in there.

For example, here’s a Page class for our Watin test page, along with the refactored unit tests.

using WatiN.Core;

namespace test
{
    public class WatinTestPage
    {
        private readonly IE browser;

        public WatinTestPage(IE browser)
        {
            this.browser = browser;
        }

        public string MyTextArea
        {
            get { return browser.TextField("MyTextArea").Text; }
        }

        public void SetMyTextArea(string myTextArea)
        {
            browser.TextField("MyTextArea").TypeText(myTextArea);
        }

        // same for other controls

        public ElementCollection GetTableRow(int row)
        {
            Table table = browser.Table("MyTable");
            TableRowCollection tableRows = table.TableRows;
            TableRow tableRow = tableRows[row];
            return tableRow.Elements;
        }

        public string TableName(int row)
        {
            ElementCollection rowData = GetTableRow(row);
            return rowData[0].OuterText;
        }

        public string TablePhoneNumber(int row)
        {
            ElementCollection rowData = GetTableRow(row);
            return rowData[1].OuterText;
        }
    }
}
using NUnit.Framework;
using test;
using WatiN.Core;

namespace tests
{
    [TestFixture]
    public class WatinTest
    {
        [Test]
        public void SetTextArea()
        {
            using (IE browser = new IE("http://localhost:4642/Home/WatinTestPage"))
            {
                WatinTestPage page = new WatinTestPage(browser);
                page.SetMyTextArea("I am changing you ...");
                Assert.AreEqual("I am changing you ...", page.MyTextArea);
            }
        }

        [Test]
        public void ParseTheTableNicely()
        {
            using (IE browser = new IE("http://localhost:4642/Home/WatinTestPage"))
            {
                WatinTestPage page = new WatinTestPage(browser);
                Assert.AreEqual("Paul", page.TableName(1));
                Assert.AreEqual("403 111 1111", page.TablePhoneNumber(1));
                Assert.AreEqual("Peter", page.TableName(2));
                Assert.AreEqual("403 222 2222", page.TablePhoneNumber(2));
            }
        }
}

See how much that cleans things up?

Next stop we’ll look at how to incorporate Watin tests into your MS-Build.

Saving Private Ryan

Leave a comment

Saving Private Ryan

I am sick.
I’ve got a cold.
My throat is burning.
My nose is runny.
My family is away on vacation (which is probably a good thing).
And I should be in bed, sleeping, and generally feeling sorry for myself like most men when they get a cold.

But I am not.
I am here, at Starbucks, on a Friday night, totally pumped and just feeling lucky to be alive, because I just finished watching the first thirty minutes of one greatest movies ever—Saving Private Ryan.

You think you’ve got problems?

Watch Saving Private Ryan.
Then tell me you’ve got a problem.

Watch the first 27 minutes of this film and tell me tomorrow you have to get up, and storm the beaches of Normandy.

Tell me you just had to type the letter to the mother of a soldier who just lost her third son to combat.

Didn’t get that promotion?
Didn’t get invited out for beers with your friends?
Your iPhone 4 antenna not quite working the way you’d like?

You have no idea how lucky you are to be alive.
Much less be one of the lucky sperm to be born in one of the of the most amazing, privileged countries in the world.

Why I love this movie

Saving Private Ryan is more than than a Academy Award winning movie about a group of soldiers sent out to find and safely return the last son of four of a family whose sons all volunteered to fight in the Second World War.

It’s a wake up call, to you and me, to stop feeling sorry for ourselves, and to appreciate every God given day you and I have to be alive, here on the planet, to do as much, or as little, as we like.

Watch (or read) this scene where General George C.Marshall reads a letter to his staff about why they are going after Private Ryan.

Marshall: I have a letter here, written a long time ago to a Mrs. Bixby in Boston. So bear with me.

Dear Madam,

I have been shown in the files of the War Department a statement of the Adjutant General of Massachusetts that you are the mother of five sons who have died gloriously on the field of battle.

I feel how weak and fruitless must be any words of mine that would attempt to beguile you from the grief of a loss so overwhelming. But I cannot refrain from tendering to you the consolation that may be found in the thanks of the Republic they died to save.

I pray that our Heavenly Father may assuage the anguish of your bereavement, and leave you only the cherished memory of the loved, lost, and the solemn pride that must be yours to have laid so costly a sacrifice upon the altar of freedom.

Yours, very sincerely and respectfully,

Abraham Lincoln

Marshall: The boy’s alive. We are going to send somebody to find him. And we are going to get him the hell out of there.

Staff: Yes, sir….

If this scene doesn’t bring a tear to your eye you are made of stone.

You have no problems

So if you are feeling down, need some perspective, and you don’t know who to turn to, pop Saving Private Ryan into your BlueRay, or PVR it like I did, and let one of the greatest war movies ever bring your pity party to an end.

I guarantee you. What ever conceivable problems you think you have, won’t be so big when compared to what those Son of guns went through when they stormed the beaches of Normandy.

Getting started with Watin, NUnit, and MVC.NET

2 Comments

Watin is a web application testing framework handy for writing high-level smoke screen tests against your .NET web application.

The website has a decent getting started section but I ran into one gotcha (really just a missing dll) and wanted to show you how to get it up and running quickly and easily using NUnit on a simple MVC.NET application.

Step 1: Download Watin

You can download Watin from the main website or just click here and download the lastest Watin 2.x release candidate.

Step 2: Create an empty web application.

For this example I created an empty ‘ASP.NET MVC2 Web Application’ and then added a ‘Class Library’ project to hold my Watin unit tests.

Step 3: Add references.

To run the Watin tests you need two dlls:

  • Watin.Core.dll
  • Interop.SHDocVw.dll

Add these (as well as nunit.framework.dll) to your unit test class library.

Step 4: Create config file to set thread state

Because Internet Explorer is not thread safe, we need to configure NUnit to run in single thread state mode (more details on why here).

Add a ‘Application Configuration File’ (i.e. App.config) to your unit test dll

and paste the following into your configuration file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
   <sectionGroup name="NUnit">
    <section name="TestRunner" type="System.Configuration.NameValueSectionHandler"/>
   </sectionGroup>
  </configSections>
  <NUnit>
   <TestRunner>
    <!-- Valid values are STA,MTA. Others ignored. -->
    <add key="ApartmentState" value="STA" />
   </TestRunner>
  </NUnit>
</configuration>

Step 5: Write your test(s)

The Watin Getting Started section has a simple example to get you going.

using NUnit.Framework;
using WatiN.Core;

namespace tests
{
    [TestFixture]
    public class WatinTest
    {
        [Test]
        public void HelloGoogle()
        {
            // Open a new Internet Explorer window and
            // goto the google website.
            IE ie = new IE("http://www.google.com");

            // Find the search text field and type Watin in it.
            ie.TextField(Find.ByName("q")).TypeText("WatiN");

            // Click the Google search button.
            ie.Button(Find.ByValue("Google Search")).Click();

            // Uncomment the following line if you want to close
            // Internet Explorer and the console window immediately.
            //ie.Close();
        }
    }
}

When you run this test, your default browser should pop-up, enter ‘Watin’ in the search box, and then click the search button.

To run a test against your MVC.NET application, you need to start your webserver. Hit F5 to run your application, note the URL it starts up on (i.e. http://localhost:1110), and then edit the test below so it looks something like this:

        [Test]
        public void HelloMVC()
        {
            IE ie = new IE("http://localhost:1110");
            Assert.IsTrue(ie.Text.Contains("My MVC Application"));
        }

Congratulations! You’ve just written your first Watin test.

Next week we will dive deeper and look more closely at some specific Watin controls and how they work.

Try twice

Leave a comment

I am still a big believer in throwing away code after 4pm (or whatever time of day you stop being productive).

But taking a stab at a hairy problem, throwing it all away, and then trying again the next day (or trying something twice) can work wonders when faced with sticky problems.

For one you are under no pressure.
It’s the end of the day—you are going to throw it away anyways.
No big deal.

Also you are guaranteed to learn something.
You may not solve it, but you’ll know where the traps are for the following morning.

So the next time you reach the end of the day and are considering surfing the web or checking your blog for the umpteenth time.
Take a swing at that hairy problem instead.

It’ll be easier to solve the next day.
And it may not be as bad as you think.

John Wooden on Success

2 Comments

John Wooden was one of America’s greatest coaches.

He built a sports dynasty coaching the UCLA Bruins winning 10 national championships,7 in a row, from 1967 – 1973.

He was awarded the Presidential Medal of Freedom in 2003.

And six years later The Sporting News selected him the greatest coach in American sports history.

John passed away this year, but in this Charlie Rose interview, John shares what I think is one of the best definitions of success I have ever heard.

Success is piece of mind attained only through self satisfaction and knowing you made the effort.
Do the best of which you are capable.

Don’t try and be better than someone else.
Just make the effort to be the best you can.

Don’t expect to make tremendous improvements each day.
Make a little each day.

Make each day your masterpiece.

That’s what my dad always taught me: “Just to do your best.”
Take comfort in knowing you gave it your all because at the end of the day, what else can you do?

While looking for more John Wooden perls of wisdom I came across this TED video.

Here’s another poem that helped John form his philosophy towards life, coaching, and teaching.

No written word,
No spoken plea,
Can teach our youth what they should be.
Nor all the books on all the shelves,
It’s what the teachers are themselves.

This world was a better place for John Wooden. He will be sorely missed.

How to make really important life decisions

3 Comments

You are going to face some pretty important decisions in your life time.

  • Should I take that job?
  • Is this the right partner for me?
  • Should I get the 13″ or 15″ MacBook Pro?

Now before we get to how to make these tough choices, understand one thing:

At the end of the day it doesn’t really matter.

Eventually we are all going to die.
A thousand years from now no one will really care.
And it doesn’t really matter all the much on the grand scheme of things.

So relax.

When faced with a sticky decision simply do this:

Imagine you are on your death bed, and ask yourself if you would regret not doing X, Y, or Z when you were younger.

If the answer if yes, go for it!

There is nothing worse than living a life of regret.
And, no, that doesn’t mean you should just go out there and do dumb things.
Especially if you have a family and it’s no longer all about you.

But as Steve Jobs would say, it’s OK to be a little bit foolish and this is how Jeff Bezos (founder of Amazon.com) makes important decisions too.

So the next time you are facing a life altering decision, simply cast yourself into the future, and die before you die.

You won’t regret it.

More is less also applies to pictures

Leave a comment

Most of us are aware that less is more when it comes to communication.

I would have written you a shorter letter but I didn’t have the time. — derived from Blaise Pascal, Provincial Letters XVI.

This same rule applies when it comes to pictures.

Here an image I used in The Agile Samurai to explain one of the two pillars of agile analysis—just-in-time analysis.

This is a powerful concept and there were a lot of points I wanted to make with this picture.

It’s a good image.
Get’s the point across.
But the reader has to work too hard to figure out what I am really trying to say.

Here is the same image, but with fewer lines and less noise.

Much better. Intent jumps right off the page.

I don’t have a systematic way of determine when removing a line or word makes sense and when it doesn’t.

Best advice I can offer to to draw your art both ways and see what feels better.

So the next time you are preparing that killer graphic, see if there are any lines or words you could remove before hitting the save button.

You’ll audience will appreciate the clarity and you will stand a greater chance of getting your point across.

Older Entries