JagaScript

Logo
2 min read

Using Custom Terminal Functions

February 27, 2019
tags: terminal, tips

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


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


Commit for a typoe fix

typo() {
    git commit -am "fix typo ✍ "
}

Commit for dead code elimination (like remove unused import)

#remove dead code
rdc() {
  git commit -am "remove unused code ☠️ "
}

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

Sharing is caring

Blog by Jaga Santagostino.
Software consultant, polyglot developer, maker of things, lifelong learner.
ReactJS Milano & milano.dev organizer