betty: A Slightly Better cp

betty is a simple command line tool which combines the functionality of cp and mkdir into one command.

betty: A Slightly Better cp

Lately I found myself repeatedly running into the same silly issue: I want to copy a file to a directory but the directory doesn't exist.

The obvious solution is to run mkdir target_directory && cp source_file target_directory. However, if the desitination directory was many steps away it was a pain to tab it out twice in a row. There had to be a better way.

I decided to write a simple bash command that copies files and makes the appropriate directories if necessary, thus saving me a step (and a couple of keystrokes) in my day to day command line use. This is one of the first bash scripts I've ever written, so I apologize if the syntax doesn't follow conventions.

The important part of the command looks like this:


for file in $source_files; do
    if [[ ! $file == "-"* ]]; then
        if [[ ! -e $file ]]; then
            die "one or more source files do not exist"

target="${@: -1}"
mkdir -p $target 2> /dev/null
cp "$@"

You can see the full source code in this Github repository.

If you'd like to use this command:

$ curl -LOk
$ ln -s betty /usr/local/bin
$ chmod +x /usr/local/bin/betty

Make sure that /usr/local/bin is in your PATH. If it isn't, you can add export PATH="$PATH:/usr/local/bin" to your .bash_profile and then source it.

This new command can now be used just as you would a normal cp command:

$ betty source_file non_existant_target_directory.

As always, thanks for reading and feel free to follow me on Twitter @brodan_ to keep up with future blog posts.