Bash Alias, Functions, and Executable Scripts

2018-10-21

I used to be intimidated of the terminal, because there was no graphical user interface (GUI). Now, I like using terminal because whole worlds (aka command line interfaces [CLI]) can be created for a framework’s development ecosystem, like React CLI and Vue CLI.

That said, there’s the Bash kernel, which oversees all these CLIs. I’ve learned a few Bash scripts that I plan to share today.

In this post:

  • Bash
    • Alias
    • Functions
    • Executable Scripts

Bash Alias

Bash aliases are stored in the .bash_profile. When listing several commands, separate them with semicolons (;).

  • $1 = alias name
  • $2 = commands
# alias format
alias $1='$2'

# alias example
alias git-s-example='git status; git status -s'

# run the alias
git-s-example   # runs the commands that outputs 2 different ways of git status (longform and shortform)

Bash Functions

Bash functions are added to the `.bash_profile.

  • $3 = which files to git add (--all or specific file)
  • $4 = commit message
# function format
namethisfunction() {
  // do something
}

# function example
# .bash_profile
gitc() {
  git add $3
  git status -s
  git commit -m "$4"
  git status -s
  echo "########## COMPLETED ACTIONS: git add and git commit ##########"
}

# in the terminal
gitc --all "this is my commit"
# the gitc function runs and outputs here

Bash Executable Scripts

Bash executable scripts are .sh files that live anywhere you want. Executable scripts have an asterick attached at the end of the file.

  • $5 = which files to git add (--all or specific file)
  • $6 = commit message
# gitc.sh
#!/bin/bash     # this line is required for executable script
git add $5
git status -s
git commit -m "$6"
git status -s

# in the terminal
chmod 755 gitc.sh                  # run this command to output
gitc.sh*                           # this, which has an asterick (*)
gitc.sh --all "this is my commit"  # run this command

I use this function often when I commit my files to Git.


Sources