DEV Community

Cover image for Bash function to edit scripts faster
Waylon Walker
Waylon Walker

Posted on • Originally published at waylonwalker.com

6 1

Bash function to edit scripts faster

I am often editing my own scripts as I develop them. I want to make a better workflow for working with scripts like this.

Currently

Currently I am combining nvim with a which subshell to etit these files like this.

for now lets use my todo command as an example

nvim `which todo`
Enter fullscreen mode Exit fullscreen mode

First pass

On first pass I made a bash function to do exactly what I have been doing.

ewhich () {$EDITOR `which "$1"`}
Enter fullscreen mode Exit fullscreen mode

The $1 will pass the first input to the which subshell. Now we can edit our todo script like this.

ewich todo
Enter fullscreen mode Exit fullscreen mode

Note, I use bash functions instead of aliases for things that require input.

Final State

This works fine for commands that are files, but not aliases or shell functions. Next I jumped to looking at the output of command -V $1.

  • if the command is not found, search for a file
  • if its a builtin, exit
  • if its an alias, open my ~/.alias file to that line
  • if its a function, open my ~/.alias file to that line
ewhich () { case `command -V $1` in
    "$1 not found")
        FILE=`fzf --prompt "$1 not found searching ..." --query $1`
        [ -z "$FILE" ] && echo "closing" || $EDITOR $FILE;;
    *"is a shell builtin"*)
        echo "$1 is a builtin";;
    *"is an alias"*)
        $EDITOR ~/.alias +/alias\ $1;;
    *"is a shell function"*)
        $EDITOR ~/.alias +/^$1;;
    *)
        $EDITOR `which "$1"`;;
esac
Enter fullscreen mode Exit fullscreen mode

a bit more ergo, and less readable

To make it easier to type, at the sacrifice of readability for anyone watching I added a single character e alias to ewhich. So when I want to edit anything I just use e.

alias e=ewhich
Enter fullscreen mode Exit fullscreen mode

Results

Here is a quick screencast of how it works.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay