How do I create my own custom command line script in zsh?

Viewed 24

I want to be able to run simple one line commands on my terminal, but instead of them being complicated I want them to be very simple, writing my own commands for these complex command lines that I have to write out so frequently. I am using the zsh command line and for example I would want to do this.

% npx tailwindcss -i ./static/styles.css -o ./static/output.css --watch

into something much easier to read such as

% build tailwindcss

Another problem/example is where if I would like to use http-server, but I want to turn off the caching, I don't think you can change the default settings for http-server module to turn off the caching, I have to do this:

% http-server -c-1

I know it is not too much of a big deal but I would like to at least pretend that the zero caching is the default. So I could do something like this with the command line:

% run server

And that would just run the server.

Also as a side note if this is not the best command line tool to do stuff like this in like maybe bash would be better I would be open to using a different command line tool as well.

1 Answers

Using aliases

If you run the exact same command every time you could alias it like this:

alias http-server="http-server -c-1"
alias <alias-name>="npx tailwindcss -i ./static/styles.css -o ./static/output.css --watch"

Now http-server expands to http-server -c-1 and <alias-name> expands to npx tailwindcss -i ./static/styles.css -o ./static/output.css --watch

Using functions

If you want to choose the input file each time you could write a function instead:

build(){
    npx tailwindcss -i $1 -o ./static/output.css --watch
}

Then you can build with build file.css

Add the alias or function to ~/.zshrc if you want it available every time you start zsh

Using bck-i-search

Use Ctrl+r to search history. Pressing Ctrl+r and writing "tailwind" will likely show you the full command. You can even comment the function with some arbitrary words to make them easier to find in history (e.g. "aaa")

npx tailwindcss -i ./static/styles.css -o ./static/output.css --watch #aaa
Related