wdahab
wdahab

Reputation: 357

OSX "open" command to create new files with an app

So, I like to use TextWrangler for editing code in OSX, and I tend to use a terminal to control my workflow. Generally, I use a bash alias:

alias text='open -a /Applications/TextWrangler.app'

However, this method doesn't allow me to open new files on the fly from the prompt. For example, if I typed emacs newfile.py it would temporarily create a new file, but not touch it until I actually saved the file. With my alias, though, if newfile.py doesn't exist, then I get an error, and have to manually touch the file then open it.

Any suggestions on hidden ways to use open that solve this? Or third-party alternatives to the open command? Or is this just a fundamental limitation of GUI-based editors?

Upvotes: 2

Views: 1481

Answers (3)

Chuck
Chuck

Reputation: 237030

I think you want a full-fledged shell script rather than just an alias. Make a file with these contents:

if [ -e "$1" ]; then
  open -a TextWrangler -- "$1"
else
  touch "$1"
  open -a TextWrangler -- "$1"
fi

Save it as text somewhere in your PATH and chmod it to be executable and you're golden.

If you really want to make it so that the file doesn't exist if you don't save it, that's trickier. I think you'll have to do something like this:

if [ -e "$1" ]; then
  open -a TextWrangler -- "$1"
else
  touch "$1"
  open -a TextWrangler -- "$1"
  sleep 1
  rm "$1"
fi

This will actually create the file and then delete it one second later. The app will still have the file open, though, so that when you save it will be recreated.

Upvotes: 1

jaypal singh
jaypal singh

Reputation: 77095

How about just create a function instead of an alias in your starup file (.bashrc, .profile etc).

newf() {
    echo "$1" | xargs touch; open -a "/Applications/TextWrangler.app" "$1"
} 

Once added, source your startup script and just do the following to use this -

newf dummyfile.txt

and Text Wrangler will pop up with an empty file called dummyfile.txt.

Upvotes: 2

Paul R
Paul R

Reputation: 212959

If you get TextWrangler's big brother BBEdit then it comes with command line tools bbedit and bbdiff which give you the behaviour you are looking for plus a lot of other useful functionality.

Upvotes: 0

Related Questions