loading...
Cover image for Useful functions and commands for Bash

Useful functions and commands for Bash

octaneinteractive profile image Wayne Smallman ・2 min read

I'll be honest, the command line was once a terrifying place. I remember when Mac OS X launched, and there it was, the Terminal — the name encapsulated the fear I had towards it.

But I persisted, and what was once fear is now a friendship (though not reciprocal).

Taming the Beast took a while, for sure, but I'm at a point where I'm able to do useful things in Bash, like create aliases and functions.

So here are two functions I use a lot, which I've decided to share in the hope someone finds them useful, too!

Before taking the plunge, be sure to create a copy of ".bash_profile" first!

nano ~/.bash_profile

Also, feel free to rename the functions.

Edit a file with a native application

I'm no command line hero, so when it comes to editing big files and making multi-line edits, I like to use something native:

wsef () {
    # edit file.
    # Usage: wsef file_name
    # Default application.
    APP="BBEdit"
    if [ "$1" ]; then
        open -a $APP $1
    else
        echo "A file name is required."
        return
    fi
}

If required, swap out "BBEdit" for something else.

Find a command

The up arrow key is perfect for the first ten previous commands, but then I need something else:

wsfc () {
    # find command.
    # Usage: wsfc term
    if [ "$1" ]; then
        history | grep -i $1
    else
        echo "A search term is required."
        return
    fi
}

Also, as an added a bonus:

export HISTTIMEFORMAT="%d/%m/%y %T "

... which adds a timestamp to the search results, or whenever you run the history command.

Extras

If you're a cat lover like me:

cat -n name_of_file

... and you'll see line numbers.

And for those who've got themselves stuck in vi as I have:

  1. press "i"
  2. make an edit, if you dare
  3. press "esc"
  4. write ":wq"
  5. then press enter

Have fun!

Discussion

pic
Editor guide