DEV Community

Jaga santagostino
Jaga santagostino

Posted on • Originally published at jagascript.com on

Using Custom Terminal Functions

Did you know you can declare a custom function to use in your terminal?

There’s dozens of operations you perform daily in your terminal that can be automated with very little effort, one way is using a custom function.

How do functions in bash/zsh work? Here’s a little example:

function sayCiaone() {
    echo "ciaone from a shell function"
}

copy this in your terminal and then call sayCiaone


Here’s some functions that I use daily

create folder and cd into it

function mkcd() {
    mkdir -p "$1" && cd "$1"
}

$1 is the first parameter after mkcd for calling mkcd my-new-folder is essentially like typing

mkdir my-new-folder
cd my-new-folder

pasting clipboard content in a file

function pastefile() {
    pbpaste > "$1"
}
  • pbpaste is a builtin utility on macOS that print the clipboard content
  • > means to write the input from the left (the output of the command pbpaste)
  • $1 is the argument, in this case, the filename I want to paste to.

pastefile myFile will create a new file named myFile with my current clipboard content


print package.json scripts

function scripts() {
     cat package.json | jq -r '.scripts'
}

scripts

  • | is the pipe operator in shell scripting, it means the output of the command on his left will be the input of the command on his right, in this case, the content of the package.json file
  • jq is a utility for formatting and pretty printing JSON, in this case we only read the field scripts of the received object

commit everything with a wip commit message

function wip() {
    git add --all
    git commit -m "wip"
}

this is pretty self-explanatory :D

tips

  • in zsh you can set the function as a oneline
  • in zsh function keyword is optional

the snippet below is valid in zsh

mkcd() { mkdir -p "$1" && cd "$1" }

Saving in a dotfile for reuse

declaring a function only makes it available in the current terminal session, if you want it to be persisted and accessible from any terminal you can declare them inside your .zshrc or .bashrc

UPDATE

Looks like the function keyword is optional

this code is actually valid in both zsh and bash

sayCiaone() {
echo "ciaone from a shell function"
}

thanks to @moopet

Top comments (2)

Collapse
 
moopet profile image
Ben Sinclair

The function keyword is optional (and discouraged) in Bash, too.

Collapse
 
jaga profile image
Jaga santagostino • Edited

Nice, I didn't knew that