Initial Oh My Bash framework

This commit is contained in:
Toan Nguyen 2017-03-19 15:40:25 +07:00
commit adc673b02a
23 changed files with 2169 additions and 0 deletions

11
.gitignore vendored Normal file

@ -0,0 +1,11 @@
# custom files
custom/
!custom/plugins/example
!custom/example.sh
# temp files directories
cache/
log/
# disabled files
*.disabled

13
LICENSE Normal file

@ -0,0 +1,13 @@
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2017 Toan Nguyen <destro.nnt@gmail.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.

205
README.md Normal file

@ -0,0 +1,205 @@
Oh My Bash is an open source, community-driven framework for managing your [bash](https://www.gnu.org/software/bash/) configuration.
Sounds boring. Let's try again.
Oh My Bash will not make you a 10x developer...but you might feel like one.
Once installed, your terminal shell will become the talk of the town or your money back! With each keystroke in your command prompt, you'll take advantage of the hundreds of powerful plugins and beautiful themes. Strangers will come up to you in cafés and ask you, "that is amazing! are you some sort of genius?"
Finally, you'll begin to get the sort of attention that you have always felt you deserved. ...or maybe you'll use the time that you're saving to start flossing more often.
## Getting Started
### Prerequisites
__Disclaimer:__ _Oh My Bash works best on macOS and Linux._
* Unix-like operating system (macOS or Linux)
* `curl` or `wget` should be installed
* `git` should be installed
### Basic Installation
Oh My Bash is installed by running one of the following commands in your terminal. You can install this via the command-line with either `curl` or `wget`.
#### via curl
```shell
sh -c "$(curl -fsSL https://raw.githubusercontent.com/nntoan/oh-my-bash/master/tools/install.sh)"
```
#### via wget
```shell
sh -c "$(wget https://raw.githubusercontent.com/nntoan/oh-my-bash/master/tools/install.sh -O -)"
```
## Using Oh My Bash
### Plugins
Oh My Bash comes with a shit load of plugins to take advantage of. You can take a look in the [plugins](https://github.com/nntoan/oh-my-bash/tree/master/plugins) directory and/or the [wiki](https://github.com/nntoan/oh-my-bash/wiki/Plugins) to see what's currently available.
#### Enabling Plugins
Once you spot a plugin (or several) that you'd like to use with Oh My Bash, you'll need to enable them in the `.bashrc` file. You'll find the bashrc file in your `$HOME` directory. Open it with your favorite text editor and you'll see a spot to list all the plugins you want to load.
For example, this line might begin to look like this:
```shell
plugins=(git bundler osx rake ruby)
```
#### Using Plugins
Most plugins (should! we're working on this) include a __README__, which documents how to use them.
### Themes
We'll admit it. Early in the Oh My Bash world, we may have gotten a bit too theme happy. We have over one hundred themes now bundled. Most of them have [screenshots](https://wiki.github.com/nntoan/oh-my-bash/themes) on the wiki. Check them out!
#### Selecting a Theme
_Powerline's theme is the default one. It's not the fanciest one. It's not the simplest one. It's just the right one (for me)._
Once you find a theme that you want to use, you will need to edit the `~/.bashrc` file. You'll see an environment variable (all caps) in there that looks like:
```shell
OSH_THEME="powerline"
```
To use a different theme, simply change the value to match the name of your desired theme. For example:
```shell
OSH_THEME="agnoster" # (this is one of the fancy ones)
# you might need to install a special Powerline font on your console's host for this to work
# see https://github.com/nntoan/oh-my-bash/wiki/Themes#agnoster
```
Open up a new terminal window and your prompt should look something like this:
![Agnoster theme](https://cloud.githubusercontent.com/assets/2618447/6316862/70f58fb6-ba03-11e4-82c9-c083bf9a6574.png)
In case you did not find a suitable theme for your needs, please have a look at the wiki for [more of them](https://github.com/nntoan/oh-my-bash/wiki/External-themes).
If you're feeling feisty, you can let the computer select one randomly for you each time you open a new terminal window.
```shell
OSH_THEME="random" # (...please let it be pie... please be some pie..)
```
## Advanced Topics
If you're the type that likes to get their hands dirty, these sections might resonate.
### Advanced Installation
Some users may want to change the default path, or manually install Oh My Bash.
#### Custom Directory
The default location is `~/.oh-my-bash` (hidden in your home directory)
If you'd like to change the install directory with the `OSH` environment variable, either by running `export OSH=/your/path` before installing, or by setting it before the end of the install pipeline like this:
```shell
export OSH="$HOME/.dotfiles/oh-my-bash"; sh -c "$(curl -fsSL https://raw.githubusercontent.com/nntoan/oh-my-bash/master/tools/install.sh)"
```
#### Manual Installation
##### 1. Clone the repository:
```shell
git clone git://github.com/nntoan/oh-my-bash.git ~/.oh-my-bash
```
##### 2. *Optionally*, backup your existing `~/.bashrc` file:
```shell
cp ~/.bashrc ~/.bashrc.orig
```
##### 3. Create a new sh configuration file
You can create a new sh config file by copying the template that we have included for you.
```shell
cp ~/.oh-my-bash/templates/bashrc.osh-template ~/.bashrc
```
##### 4. Reload your .bashrc
```shell
source ~/.bashrc
```
##### 5. Initialize your new bash configuration
Once you open up a new terminal window, it should load sh with Oh My Bash's configuration.
### Installation Problems
If you have any hiccups installing, here are a few common fixes.
* You _might_ need to modify your `PATH` in `~/.bashrc` if you're not able to find some commands after switching to `oh-my-bash`.
* If you installed manually or changed the install location, check the `OSH` environment variable in `~/.bashrc`.
### Custom Plugins and Themes
If you want to override any of the default behaviors, just add a new file (ending in `.sh`) in the `custom/` directory.
If you have many functions that go well together, you can put them as a `XYZ.plugin.sh` file in the `custom/plugins/` directory and then enable this plugin.
If you would like to override the functionality of a plugin distributed with Oh My Bash, create a plugin of the same name in the `custom/plugins/` directory and it will be loaded instead of the one in `plugins/`.
## Getting Updates
By default, you will be prompted to check for upgrades every few weeks. If you would like `oh-my-bash` to automatically upgrade itself without prompting you, set the following in your `~/.bashrc`:
```shell
DISABLE_UPDATE_PROMPT=true
```
To disable automatic upgrades, set the following in your `~/.bashrc`:
```shell
DISABLE_AUTO_UPDATE=true
```
### Manual Updates
If you'd like to upgrade at any point in time (maybe someone just released a new plugin and you don't want to wait a week?) you just need to run:
```shell
upgrade_oh_my_bash
```
Magic!
## Uninstalling Oh My Bash
Oh My Bash isn't for everyone. We'll miss you, but we want to make this an easy breakup.
If you want to uninstall `oh-my-bash`, just run `uninstall_oh_my_bash` from the command-line. It will remove itself and revert your previous `bash` configuration.
## Contributing
I'm far from being a [Bash](https://www.gnu.org/software/bash/) expert and suspect there are many ways to improve if you have ideas on how to make the configuration easier to maintain (and faster), don't hesitate to fork and send pull requests!
We also need people to test out pull-requests. So take a look through [the open issues](https://github.com/nntoan/oh-my-bash/issues) and help where you can.
### Do NOT send us themes
We have (more than) enough themes for the time being. Please add your theme to the [external themes](https://github.com/nntoan/oh-my-bash/wiki/External-themes) wiki page.
## Contributors
Oh My Bash has a vibrant community of happy users and delightful contributors. Without all the time and help from our contributors, it wouldn't be so awesome.
Thank you so much!
## License
Oh My Bash is released under the [WTFPL license](LICENSE.txt).

100
lib/functions.sh Normal file

@ -0,0 +1,100 @@
function bash_stats() {
fc -l 1 | awk '{CMD[$2]++;count++;}END { for (a in CMD)print CMD[a] " " CMD[a]/count*100 "% " a;}' | grep -v "./" | column -c3 -s " " -t | sort -nr | nl | head -n20
}
function uninstall_oh_my_bash() {
env OSH=$OSH sh $OSH/tools/uninstall.sh
}
function upgrade_oh_my_bash() {
env OSH=$OSH sh $OSH/tools/upgrade.sh
}
function take() {
mkdir -p $1
cd $1
}
function open_command() {
emulate -L zsh
setopt shwordsplit
local open_cmd
# define the open command
case "$OSTYPE" in
darwin*) open_cmd='open' ;;
cygwin*) open_cmd='cygstart' ;;
linux*) open_cmd='xdg-open' ;;
msys*) open_cmd='start ""' ;;
*) echo "Platform $OSTYPE not supported"
return 1
;;
esac
# don't use nohup on OSX
if [[ "$OSTYPE" == darwin* ]]; then
$open_cmd "$@" &>/dev/null
else
nohup $open_cmd "$@" &>/dev/null
fi
}
#
# Get the value of an alias.
#
# Arguments:
# 1. alias - The alias to get its value from
# STDOUT:
# The value of alias $1 (if it has one).
# Return value:
# 0 if the alias was found,
# 1 if it does not exist
#
function alias_value() {
alias "$1" | sed "s/^$1='\(.*\)'$/\1/"
test $(alias "$1")
}
#
# Try to get the value of an alias,
# otherwise return the input.
#
# Arguments:
# 1. alias - The alias to get its value from
# STDOUT:
# The value of alias $1, or $1 if there is no alias $1.
# Return value:
# Always 0
#
function try_alias_value() {
alias_value "$1" || echo "$1"
}
#
# Set variable "$1" to default value "$2" if "$1" is not yet defined.
#
# Arguments:
# 1. name - The variable to set
# 2. val - The default value
# Return value:
# 0 if the variable exists, 3 if it was set
#
function default() {
test `typeset +m "$1"` && return 0
typeset -g "$1"="$2" && return 3
}
#
# Set enviroment variable "$1" to default value "$2" if "$1" is not yet defined.
#
# Arguments:
# 1. name - The env variable to set
# 2. val - The default value
# Return value:
# 0 if the env variable exists, 3 if it was set
#
function env_default() {
env | grep -q "^$1=" && return 0
export "$1=$2" && return 3
}

217
lib/git.sh Normal file

@ -0,0 +1,217 @@
# Outputs current branch info in prompt format
function git_prompt_info() {
local ref
if [[ "$(command git config --get oh-my-bash.hide-status 2>/dev/null)" != "1" ]]; then
ref=$(command git symbolic-ref HEAD 2> /dev/null) || \
ref=$(command git rev-parse --short HEAD 2> /dev/null) || return 0
echo "$OSH_THEME_GIT_PROMPT_PREFIX${ref#refs/heads/}$(parse_git_dirty)$OSH_THEME_GIT_PROMPT_SUFFIX"
fi
}
# Checks if working tree is dirty
function parse_git_dirty() {
local STATUS=''
local FLAGS
FLAGS=('--porcelain')
if [[ "$(command git config --get oh-my-bash.hide-dirty)" != "1" ]]; then
if [[ $POST_1_7_2_GIT -gt 0 ]]; then
FLAGS+='--ignore-submodules=dirty'
fi
if [[ "$DISABLE_UNTRACKED_FILES_DIRTY" == "true" ]]; then
FLAGS+='--untracked-files=no'
fi
STATUS=$(command git status ${FLAGS} 2> /dev/null | tail -n1)
fi
if [[ -n $STATUS ]]; then
echo "$OSH_THEME_GIT_PROMPT_DIRTY"
else
echo "$OSH_THEME_GIT_PROMPT_CLEAN"
fi
}
# Gets the difference between the local and remote branches
function git_remote_status() {
local remote ahead behind git_remote_status git_remote_status_detailed
remote=${$(command git rev-parse --verify ${hook_com[branch]}@{upstream} --symbolic-full-name 2>/dev/null)/refs\/remotes\/}
if [[ -n ${remote} ]]; then
ahead=$(command git rev-list ${hook_com[branch]}@{upstream}..HEAD 2>/dev/null | wc -l)
behind=$(command git rev-list HEAD..${hook_com[branch]}@{upstream} 2>/dev/null | wc -l)
if [[ $ahead -eq 0 ]] && [[ $behind -eq 0 ]]; then
git_remote_status="$OSH_THEME_GIT_PROMPT_EQUAL_REMOTE"
elif [[ $ahead -gt 0 ]] && [[ $behind -eq 0 ]]; then
git_remote_status="$OSH_THEME_GIT_PROMPT_AHEAD_REMOTE"
git_remote_status_detailed="$OSH_THEME_GIT_PROMPT_AHEAD_REMOTE_COLOR$OSH_THEME_GIT_PROMPT_AHEAD_REMOTE$((ahead))%{$reset_color%}"
elif [[ $behind -gt 0 ]] && [[ $ahead -eq 0 ]]; then
git_remote_status="$OSH_THEME_GIT_PROMPT_BEHIND_REMOTE"
git_remote_status_detailed="$OSH_THEME_GIT_PROMPT_BEHIND_REMOTE_COLOR$OSH_THEME_GIT_PROMPT_BEHIND_REMOTE$((behind))%{$reset_color%}"
elif [[ $ahead -gt 0 ]] && [[ $behind -gt 0 ]]; then
git_remote_status="$OSH_THEME_GIT_PROMPT_DIVERGED_REMOTE"
git_remote_status_detailed="$OSH_THEME_GIT_PROMPT_AHEAD_REMOTE_COLOR$OSH_THEME_GIT_PROMPT_AHEAD_REMOTE$((ahead))%{$reset_color%}$OSH_THEME_GIT_PROMPT_BEHIND_REMOTE_COLOR$OSH_THEME_GIT_PROMPT_BEHIND_REMOTE$((behind))%{$reset_color%}"
fi
if [[ -n $OSH_THEME_GIT_PROMPT_REMOTE_STATUS_DETAILED ]]; then
git_remote_status="$OSH_THEME_GIT_PROMPT_REMOTE_STATUS_PREFIX$remote$git_remote_status_detailed$OSH_THEME_GIT_PROMPT_REMOTE_STATUS_SUFFIX"
fi
echo $git_remote_status
fi
}
# Outputs the name of the current branch
# Usage example: git pull origin $(git_current_branch)
# Using '--quiet' with 'symbolic-ref' will not cause a fatal error (128) if
# it's not a symbolic ref, but in a Git repo.
function git_current_branch() {
local ref
ref=$(command git symbolic-ref --quiet HEAD 2> /dev/null)
local ret=$?
if [[ $ret != 0 ]]; then
[[ $ret == 128 ]] && return # no git repo.
ref=$(command git rev-parse --short HEAD 2> /dev/null) || return
fi
echo ${ref#refs/heads/}
}
# Gets the number of commits ahead from remote
function git_commits_ahead() {
if command git rev-parse --git-dir &>/dev/null; then
local commits="$(git rev-list --count @{upstream}..HEAD)"
if [[ "$commits" != 0 ]]; then
echo "$OSH_THEME_GIT_COMMITS_AHEAD_PREFIX$commits$OSH_THEME_GIT_COMMITS_AHEAD_SUFFIX"
fi
fi
}
# Gets the number of commits behind remote
function git_commits_behind() {
if command git rev-parse --git-dir &>/dev/null; then
local commits="$(git rev-list --count HEAD..@{upstream})"
if [[ "$commits" != 0 ]]; then
echo "$OSH_THEME_GIT_COMMITS_BEHIND_PREFIX$commits$OSH_THEME_GIT_COMMITS_BEHIND_SUFFIX"
fi
fi
}
# Outputs if current branch is ahead of remote
function git_prompt_ahead() {
if [[ -n "$(command git rev-list origin/$(git_current_branch)..HEAD 2> /dev/null)" ]]; then
echo "$OSH_THEME_GIT_PROMPT_AHEAD"
fi
}
# Outputs if current branch is behind remote
function git_prompt_behind() {
if [[ -n "$(command git rev-list HEAD..origin/$(git_current_branch) 2> /dev/null)" ]]; then
echo "$OSH_THEME_GIT_PROMPT_BEHIND"
fi
}
# Outputs if current branch exists on remote or not
function git_prompt_remote() {
if [[ -n "$(command git show-ref origin/$(git_current_branch) 2> /dev/null)" ]]; then
echo "$OSH_THEME_GIT_PROMPT_REMOTE_EXISTS"
else
echo "$OSH_THEME_GIT_PROMPT_REMOTE_MISSING"
fi
}
# Formats prompt string for current git commit short SHA
function git_prompt_short_sha() {
local SHA
SHA=$(command git rev-parse --short HEAD 2> /dev/null) && echo "$OSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$OSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# Formats prompt string for current git commit long SHA
function git_prompt_long_sha() {
local SHA
SHA=$(command git rev-parse HEAD 2> /dev/null) && echo "$OSH_THEME_GIT_PROMPT_SHA_BEFORE$SHA$OSH_THEME_GIT_PROMPT_SHA_AFTER"
}
# Get the status of the working tree
function git_prompt_status() {
local INDEX STATUS
INDEX=$(command git status --porcelain -b 2> /dev/null)
STATUS=""
if $(echo "$INDEX" | command grep -E '^\?\? ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_UNTRACKED$STATUS"
fi
if $(echo "$INDEX" | grep '^A ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_ADDED$STATUS"
elif $(echo "$INDEX" | grep '^M ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_ADDED$STATUS"
fi
if $(echo "$INDEX" | grep '^ M ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
elif $(echo "$INDEX" | grep '^AM ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
elif $(echo "$INDEX" | grep '^ T ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_MODIFIED$STATUS"
fi
if $(echo "$INDEX" | grep '^R ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_RENAMED$STATUS"
fi
if $(echo "$INDEX" | grep '^ D ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_DELETED$STATUS"
elif $(echo "$INDEX" | grep '^D ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_DELETED$STATUS"
elif $(echo "$INDEX" | grep '^AD ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_DELETED$STATUS"
fi
if $(command git rev-parse --verify refs/stash >/dev/null 2>&1); then
STATUS="$OSH_THEME_GIT_PROMPT_STASHED$STATUS"
fi
if $(echo "$INDEX" | grep '^UU ' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_UNMERGED$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*ahead' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_AHEAD$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*behind' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_BEHIND$STATUS"
fi
if $(echo "$INDEX" | grep '^## [^ ]\+ .*diverged' &> /dev/null); then
STATUS="$OSH_THEME_GIT_PROMPT_DIVERGED$STATUS"
fi
echo $STATUS
}
# Compares the provided version of git to the version installed and on path
# Outputs -1, 0, or 1 if the installed version is less than, equal to, or
# greater than the input version, respectively.
function git_compare_version() {
local INPUT_GIT_VERSION INSTALLED_GIT_VERSION
INPUT_GIT_VERSION=(${(s/./)1})
INSTALLED_GIT_VERSION=($(command git --version 2>/dev/null))
INSTALLED_GIT_VERSION=(${(s/./)INSTALLED_GIT_VERSION[3]})
for i in {1..3}; do
if [[ $INSTALLED_GIT_VERSION[$i] -gt $INPUT_GIT_VERSION[$i] ]]; then
echo 1
return 0
fi
if [[ $INSTALLED_GIT_VERSION[$i] -lt $INPUT_GIT_VERSION[$i] ]]; then
echo -1
return 0
fi
done
echo 0
}
# Outputs the name of the current user
# Usage example: $(git_current_user_name)
function git_current_user_name() {
command git config user.name 2>/dev/null
}
# Outputs the email of the current user
# Usage example: $(git_current_user_email)
function git_current_user_email() {
command git config user.email 2>/dev/null
}
# This is unlikely to change so make it all statically assigned
POST_1_7_2_GIT=$(git_compare_version "1.7.2")
# Clean up the namespace slightly by removing the checker function
unfunction git_compare_version

28
lib/grep.sh Normal file

@ -0,0 +1,28 @@
# is x grep argument available?
grep-flag-available() {
echo | grep $1 "" >/dev/null 2>&1
}
GREP_OPTIONS=""
# color grep results
if grep-flag-available --color=auto; then
GREP_OPTIONS+=" --color=auto"
fi
# ignore VCS folders (if the necessary grep flags are available)
VCS_FOLDERS="{.bzr,CVS,.git,.hg,.svn}"
if grep-flag-available --exclude-dir=.cvs; then
GREP_OPTIONS+=" --exclude-dir=$VCS_FOLDERS"
elif grep-flag-available --exclude=.cvs; then
GREP_OPTIONS+=" --exclude=$VCS_FOLDERS"
fi
# export grep settings
alias grep="grep $GREP_OPTIONS"
# clean up
unset GREP_OPTIONS
unset VCS_FOLDERS
unfunction grep-flag-available

24
lib/history.sh Normal file

@ -0,0 +1,24 @@
## Command history configuration
if [ -z "$HISTFILE" ]; then
HISTFILE=$HOME/.bash_history
fi
HISTSIZE=10000
SAVEHIST=10000
# Show history
case $HIST_STAMPS in
"mm/dd/yyyy") alias history='fc -fl 1' ;;
"dd.mm.yyyy") alias history='fc -El 1' ;;
"yyyy-mm-dd") alias history='fc -il 1' ;;
*) alias history='fc -l 1' ;;
esac
setopt append_history
setopt extended_history
setopt hist_expire_dups_first
setopt hist_ignore_dups # ignore duplication command history list
setopt hist_ignore_space
setopt hist_verify
setopt inc_append_history
setopt share_history # share command history data

25
lib/misc.sh Normal file

@ -0,0 +1,25 @@
## jobs
setopt long_list_jobs
## pager
env_default PAGER 'less'
env_default LESS '-R'
## super user alias
alias _='sudo'
alias please='sudo'
## more intelligent acking for ubuntu users
if which ack-grep &> /dev/null; then
alias afind='ack-grep -il'
else
alias afind='ack -il'
fi
# only define LC_CTYPE if undefined
if [[ -z "$LC_CTYPE" && -z "$LC_ALL" ]]; then
export LC_CTYPE=${LANG%%:*} # pick the first entry from LANG
fi
# recognize comments
setopt interactivecomments

9
lib/nvm.sh Normal file

@ -0,0 +1,9 @@
# get the node.js version
function nvm_prompt_info() {
[[ -f "$NVM_DIR/nvm.sh" ]] || return
local nvm_prompt
nvm_prompt=$(node -v 2>/dev/null)
[[ "${nvm_prompt}x" == "x" ]] && return
nvm_prompt=${nvm_prompt:1}
echo "${OSH_THEME_NVM_PROMPT_PREFIX}${nvm_prompt}${OSH_THEME_NVM_PROMPT_SUFFIX}"
}

@ -0,0 +1,33 @@
# *_prompt_info functions for usage in your prompt
#
# Plugin creators, please add your *_prompt_info function to the list
# of dummy implementations to help theme creators not receiving errors
# without the need of implementing conditional clauses.
#
# See also lib/bzr.sh, lib/git.sh and lib/nvm.sh for
# git_prompt_info, bzr_prompt_info and nvm_prompt_info
# Dummy implementations that return false to prevent command_not_found
# errors with themes, that implement these functions
# Real implementations will be used when the respective plugins are loaded
function chruby_prompt_info hg_prompt_info pyenv_prompt_info \
rbenv_prompt_info svn_prompt_info vi_mode_prompt_info \
virtualenv_prompt_info {
return 1
}
# oh-my-bash supports an rvm prompt by default
# get the name of the rvm ruby version
function rvm_prompt_info() {
[ -f $HOME/.rvm/bin/rvm-prompt ] || return 1
local rvm_prompt
rvm_prompt=$($HOME/.rvm/bin/rvm-prompt ${=OSH_THEME_RVM_PROMPT_OPTIONS} 2>/dev/null)
[[ "${rvm_prompt}x" == "x" ]] && return 1
echo "${OSH_THEME_RVM_PROMPT_PREFIX:=(}${rvm_prompt}${OSH_THEME_RVM_PROMPT_SUFFIX:=)}"
}
# use this to enable users to see their ruby version, no matter which
# version management system they use
function ruby_prompt_info() {
echo $(rvm_prompt_info || rbenv_prompt_info || chruby_prompt_info)
}

37
lib/spectrum.sh Normal file

@ -0,0 +1,37 @@
#! /bin/bash
# A script to make using 256 colors in bash less painful.
# P.C. Shyamshankar <sykora@lucentbeing.com>
# Copied from http://github.com/sykora/etc/blob/master/zsh/functions/spectrum/
typeset -AHg FX FG BG
FX=(
reset "%{^[[00m%}"
bold "%{^[[01m%}" no-bold "%{^[[22m%}"
italic "%{^[[03m%}" no-italic "%{^[[23m%}"
underline "%{^[[04m%}" no-underline "%{^[[24m%}"
blink "%{^[[05m%}" no-blink "%{^[[25m%}"
reverse "%{^[[07m%}" no-reverse "%{^[[27m%}"
)
for color in {000..255}; do
FG[$color]="%{^[[38;5;${color}m%}"
BG[$color]="%{^[[48;5;${color}m%}"
done
OSH_SPECTRUM_TEXT=${OSH_SPECTRUM_TEXT:-Arma virumque cano Troiae qui primus ab oris}
# Show all 256 colors with color number
function spectrum_ls() {
for code in {000..255}; do
print -P -- "$code: %{$FG[$code]%}$OSH_SPECTRUM_TEXT%{$reset_color%}"
done
}
# Show all 256 colors where the background is set to specific color
function spectrum_bls() {
for code in {000..255}; do
print -P -- "$code: %{$BG[$code]%}$OSH_SPECTRUM_TEXT%{$reset_color%}"
done
}

200
lib/utils.sh Normal file

@ -0,0 +1,200 @@
#!/usr/bin/env bash
############################---Description---###################################
# #
# Summary : A collection of handy utilities and functions for bash #
# Support : destro.nnt@gmail.com #
# Created date : Mar 18,2017 #
# Latest Modified date : Mar 18,2017 #
# #
################################################################################
############################---Usage---#########################################
# source ~/path/to/directory/utils.sh
########################## Styled text output ##################################
# e_header "I am a sample script"
# e_success "I am a success message"
# e_error "I am an error message"
# e_warning "I am a warning message"
# e_underline "I am underlined text"
# e_bold "I am bold text"
# e_note "I am a note"
################# Performing simple Yes/No confirmations #######################
# seek_confirmation "Do you want to print a success message?"
# if is_confirmed; then
# e_success "Here is a success message"
# else
# e_error "You did not ask for a success message"
# fi
############ Testing if packages, apps, gems, etc. are installed ###############
# if type_exists 'git'; then
# e_success "Git good to go"
# else
# e_error "Git should be installed. It isn't. Aborting."
# exit 1
# fi
# if is_os "darwin"; then
# e_success "You are on a mac"
# else
# e_error "You are not on a mac"
# exit 1
# fi
##################### Sending notifications to Pushover ########################
# pushover "We just finished performing a lengthy task."
############################### Comparing A List ###############################
# recipes=(
# A-random-package
# bash
# Another-random-package
# git
# )
# list="$(to_install "${recipes[*]}" "$(brew list)")"
# if [[ "$list" ]]; then
# for item in ${list[@]}
# do
# echo "$item is not on the list"
# done
# else
# e_arrow "Nothing to install. You've already got them all."
# fi
################################################################################
#
# Set Colors
#
# Use colors, but only if connected to a terminal, and that terminal
# supports them.
if which tput >/dev/null 2>&1; then
ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
bold="$(tput bold)"
underline=$(tput sgr 0 1)
reset="$(tput sgr0)"
red="$(tput setaf 1)"
green="$(tput setaf 2)"
yellow="$(tput setaf 3)"
blue="$(tput setaf 4)"
purple=$(tput setaf 171)
tan=$(tput setaf 3)
else
bold=""
underline=""
reset=""
red=""
green=""
yellow=""
blue=""
purple=""
tan=""
fi
#
# Headers and Logging
#
e_header() { printf "\n${bold}${purple}========== %s ==========${reset}\n" "$@"
}
e_arrow() { printf "➜ %s\n" "$@"
}
e_success() { printf "${green}✔ %s${reset}\n" "$@"
}
e_error() { printf "${red}✖ %s${reset}\n" "$@"
}
e_warning() { printf "${tan}➜ %s${reset}\n" "$@"
}
e_underline() { printf "${underline}${bold}%s${reset}\n" "$@"
}
e_bold() { printf "${bold}%s${reset}\n" "$@"
}
e_note() { printf "${underline}${bold}${blue}Note:${reset} ${blue}%s${reset}\n" "$@"
}
#
# USAGE FOR SEEKING CONFIRMATION
# seek_confirmation "Ask a question"
# Credit: https://github.com/kevva/dotfiles
#
# if is_confirmed; then
# some action
# else
# some other action
# fi
#
seek_confirmation() {
printf "\n${bold}%s${reset}" "$@"
read -p " (y/n) " -n 1
printf "\n"
}
# Test whether the result of an 'ask' is a confirmation
is_confirmed() {
if [[ "$REPLY" =~ ^[Yy]$ ]]; then
return 0
fi
return 1
}
#
# Test whether a command exists
# $1 = cmd to test
# Usage:
# if type_exists 'git'; then
# some action
# else
# some other action
# fi
#
type_exists() {
if [ "$(type -P "$1")" ]; then
return 0
fi
return 1
}
#
# Test which OS the user runs
# $1 = OS to test
# Usage: if is_os 'darwin'; then
#
is_os() {
if [[ "${OSTYPE}" == $1* ]]; then
return 0
fi
return 1
}
#
# Pushover Notifications
# Usage: pushover "Title Goes Here" "Message Goes Here"
# Credit: http://ryonsherman.blogspot.com/2012/10/shell-script-to-send-pushover.html
#
pushover () {
PUSHOVERURL="https://api.pushover.net/1/messages.json"
API_KEY=$PUSHOVER_API_KEY
USER_KEY=$PUSHOVER_USER_KEY
DEVICE=$PUSHOVER_DEVICE
TITLE="${1}"
MESSAGE="${2}"
curl \
-F "token=${API_KEY}" \
-F "user=${USER_KEY}" \
-F "device=${DEVICE}" \
-F "title=${TITLE}" \
-F "message=${MESSAGE}" \
"${PUSHOVERURL}" > /dev/null 2>&1
}

90
oh-my-bash.sh Normal file

@ -0,0 +1,90 @@
# Check for updates on initial load...
if [ "$DISABLE_AUTO_UPDATE" != "true" ]; then
env OSH=$OSH DISABLE_UPDATE_PROMPT=$DISABLE_UPDATE_PROMPT sh -f $OSH/tools/check_for_upgrade.sh
fi
# Initializes Oh My Bash
# add a function path
fpath=($OSH/functions $OSH/completions $fpath)
# Set OSH_CUSTOM to the path where your custom config files
# and plugins exists, or else we will use the default custom/
if [[ -z "$OSH_CUSTOM" ]]; then
OSH_CUSTOM="$OSH/custom"
fi
# Set OSH_CACHE_DIR to the path where cache files should be created
# or else we will use the default cache/
if [[ -z "$OSH_CACHE_DIR" ]]; then
OSH_CACHE_DIR="$OSH/cache"
fi
# Load all of the config files in ~/.oh-my-bash/lib that end in .sh
# TIP: Add files you don't want in git to .gitignore
for config_file in $OSH/lib/*.sh; do
custom_config_file="${OSH_CUSTOM}/lib/${config_file:t}"
[ -f "${custom_config_file}" ] && config_file=${custom_config_file}
source $config_file
done
is_plugin() {
local base_dir=$1
local name=$2
test -f $base_dir/plugins/$name/$name.plugin.sh \
|| test -f $base_dir/plugins/$name/_$name
}
# Add all defined plugins to fpath. This must be done
# before running compinit.
for plugin in $plugins; do
if is_plugin $OSH_CUSTOM $plugin; then
fpath=($OSH_CUSTOM/plugins/$plugin $fpath)
elif is_plugin $OSH $plugin; then
fpath=($OSH/plugins/$plugin $fpath)
fi
done
# Figure out the SHORT hostname
if [[ "$OSTYPE" = darwin* ]]; then
# macOS's $HOST changes with dhcp, etc. Use ComputerName if possible.
SHORT_HOST=$(scutil --get ComputerName 2>/dev/null) || SHORT_HOST=${HOST/.*/}
else
SHORT_HOST=${HOST/.*/}
fi
# Load all of the plugins that were defined in ~/.bashrc
for plugin in $plugins; do
if [ -f $OSH_CUSTOM/plugins/$plugin/$plugin.plugin.sh ]; then
source $OSH_CUSTOM/plugins/$plugin/$plugin.plugin.sh
elif [ -f $OSH/plugins/$plugin/$plugin.plugin.sh ]; then
source $OSH/plugins/$plugin/$plugin.plugin.sh
fi
done
# Load all of your custom configurations from custom/
for config_file in $OSH_CUSTOM/*.sh; do
source $config_file
done
unset config_file
# Load the theme
if [ "$OSH_THEME" = "random" ]; then
themes=($OSH/themes/*theme.sh)
N=${#themes[@]}
((N=(RANDOM%N)+1))
RANDOM_THEME=${themes[$N]}
source "$RANDOM_THEME"
echo "[oh-my-bash] Random theme '$RANDOM_THEME' loaded..."
else
if [ ! "$OSH_THEME" = "" ]; then
if [ -f "$OSH_CUSTOM/$OSH_THEME.theme.sh" ]; then
source "$OSH_CUSTOM/$OSH_THEME.theme.sh"
elif [ -f "$OSH_CUSTOM/themes/$OSH_THEME.theme.sh" ]; then
source "$OSH_CUSTOM/themes/$OSH_THEME.theme.sh"
else
source "$OSH/themes/$OSH_THEME.theme.sh"
fi
fi
fi

@ -0,0 +1,199 @@
# Copyright (c) 2014, NNToan - http://about.me/nntoan
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided
# that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this list of conditions
# and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided with the distribution.
# * Neither the name of Toan Nguyen Ngoc (aka NNToan) nor the names of contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
# WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
# ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
# TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# USAGE:
# bm -a bookmarkname - saves the curr dir as bookmarkname
# bm -g bookmarkname - jumps to the that bookmark
# bm -g b[TAB] - tab completion is available
# bm -p bookmarkname - prints the bookmark
# bm -p b[TAB] - tab completion is available
# bm -d bookmarkname - deletes the bookmark
# bm -d [TAB] - tab completion is available
# bm -l - list all bookmarks
# setup file to store bookmarks
if [ ! -n "$SDIRS" ]; then
SDIRS=~/.sdirs
fi
touch $SDIRS
RED="0;31m"
GREEN="0;33m"
# main function
function bm {
option="${1}"
case ${option} in
# save current directory to bookmarks [ bm -a BOOKMARK_NAME ]
-a)
_save_bookmark "$2"
;;
# delete bookmark [ bm -d BOOKMARK_NAME ]
-d)
_delete_bookmark "$2"
;;
# jump to bookmark [ bm -g BOOKMARK_NAME ]
-g)
_goto_bookmark "$2"
;;
# print bookmark [ bm -p BOOKMARK_NAME ]
-p)
_print_bookmark "$2"
;;
# show bookmark list [ bm -l ]
-l)
_list_bookmark
;;
# help [ bm -h ]
*)
echo 'USAGE:'
echo 'bm -a <bookmark_name> - Saves the current directory as "bookmark_name"'
echo 'bm -g <bookmark_name> - Goes (cd) to the directory associated with "bookmark_name"'
echo 'bm -p <bookmark_name> - Prints the directory associated with "bookmark_name"'
echo 'bm -d <bookmark_name> - Deletes the bookmark'
echo 'bm -l - Lists all available bookmarks'
kill -SIGINT $$
exit 1
;;
esac
}
# save current directory to bookmarks
function _save_bookmark {
_bookmark_name_valid "$@"
if [ -z "$exit_message" ]; then
_purge_line "$SDIRS" "export DIR_$1="
CURDIR=$(echo $PWD| sed "s#^$HOME#\$HOME#g")
echo "export DIR_$1=\"$CURDIR\"" >> $SDIRS
fi
}
# delete bookmark
function _delete_bookmark {
_bookmark_name_valid "$@"
if [ -z "$exit_message" ]; then
_purge_line "$SDIRS" "export DIR_$1="
unset "DIR_$1"
fi
}
# jump to bookmark
function _goto_bookmark {
source $SDIRS
target="$(eval $(echo echo $(echo \$DIR_$1)))"
if [ -d "$target" ]; then
cd "$target"
elif [ ! -n "$target" ]; then
echo -e "\033[${RED}WARNING: '${1}' bashmark does not exist\033[00m"
else
echo -e "\033[${RED}WARNING: '${target}' does not exist\033[00m"
fi
}
# list bookmarks with dirname
function _list_bookmark {
source $SDIRS
# if color output is not working for you, comment out the line below '\033[1;32m' == "red"
env | sort | awk '/DIR_.+/{split(substr($0,5),parts,"="); printf("\033[0;33m%-20s\033[0m %s\n", parts[1], parts[2]);}'
# uncomment this line if color output is not working with the line above
# env | grep "^DIR_" | cut -c5- | sort |grep "^.*="
}
# print bookmark
function _print_bookmark {
source $SDIRS
echo "$(eval $(echo echo $(echo \$DIR_$1)))"
}
# list bookmarks without dirname
function _l {
source $SDIRS
env | grep "^DIR_" | cut -c5- | sort | grep "^.*=" | cut -f1 -d "="
}
# validate bookmark name
function _bookmark_name_valid {
exit_message=""
if [ -z $1 ]; then
exit_message="bookmark name required"
echo $exit_message
elif [ "$1" != "$(echo $1 | sed 's/[^A-Za-z0-9_]//g')" ]; then
exit_message="bookmark name is not valid"
echo $exit_message
fi
}
# completion command
function _comp {
local curw
COMPREPLY=()
curw=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=($(compgen -W '`_l`' -- $curw))
return 0
}
# ZSH completion command
function _compzsh {
reply=($(_l))
}
# safe delete line from sdirs
function _purge_line {
if [ -s "$1" ]; then
# safely create a temp file
t=$(mktemp -t bashmarks.XXXXXX) || exit 1
trap "rm -f -- '$t'" EXIT
# purge line
sed "/$2/d" "$1" > "$t"
mv "$t" "$1"
# cleanup temp file
rm -f -- "$t"
trap - EXIT
fi
}
# bind completion command for g,p,d to _comp
if [ $ZSH_VERSION ]; then
compctl -K _compzsh bm -g
compctl -K _compzsh bm -p
compctl -K _compzsh bm -d
compctl -K _compzsh g
compctl -K _compzsh p
compctl -K _compzsh d
else
shopt -s progcomp
complete -F _comp bm -g
complete -F _comp bm -p
complete -F _comp bm -d
complete -F _comp g
complete -F _comp p
complete -F _comp d
fi
alias s='bm -a' # Save a bookmark [bookmark_name]
alias g='bm -g' # Go to bookmark [bookmark_name]
alias p='bm -p' # Print bookmark of a path [path]
alias d='bm -d' # Delete a bookmark [bookmark_name]

262
plugins/core/core.plugin.sh Normal file

@ -0,0 +1,262 @@
# ---------------------------------------------------------------------------
#
# Description: This file holds all my BASH configurations and aliases
#
# Sections:
# 1. Make Terminal Better (remapping defaults and adding functionality)
# 2. File and Folder Management
# 3. Searching
# 4. Process Management
# 5. Networking
# 6. System Operations & Information
# 7. Date & Time Management
# 8. Web Development
# 9. Reminders & Notes
#
# ---------------------------------------------------------------------------
# -----------------------------
# 1. MAKE TERMINAL BETTER
# -----------------------------
alias cp='cp -iv' # Preferred 'cp' implementation
alias mv='mv -iv' # Preferred 'mv' implementation
alias mkdir='mkdir -pv' # Preferred 'mkdir' implementation
alias ll='ls -lAFh' # Preferred 'ls' implementation
alias less='less -FSRXc' # Preferred 'less' implementation
alias nano='nano -W -$' # Preferred 'nano' implementation
alias wget='wget -c' # Preferred 'wget' implementation (resume download)
cd() { builtin cd "$@"; ll; } # Always list directory contents upon 'cd'
alias cd..='cd ../' # Go back 1 directory level (for fast typers)
alias ..='cd ../' # Go back 1 directory level
alias ...='cd ../../' # Go back 2 directory levels
alias .3='cd ../../../' # Go back 3 directory levels
alias .4='cd ../../../../' # Go back 4 directory levels
alias .5='cd ../../../../../' # Go back 5 directory levels
alias .6='cd ../../../../../../' # Go back 6 directory levels
alias dud='du -d 1 -h' # Short and human-readable file listing
alias duf='du -sh *' # Short and human-readable directory listing
alias ~="cd ~" # ~: Go Home
alias c='clear' # c: Clear terminal display
alias path='echo -e ${PATH//:/\\n}' # path: Echo all executable Paths
alias show_options='shopt' # Show_options: display bash options settings
alias fix_stty='stty sane' # fix_stty: Restore terminal settings when screwed up
alias cic='set completion-ignore-case On' # cic: Make tab-completion case-insensitive
alias h='history | grep $1' # h: Find an executed command in .bash_history
alias src='source ~/.bashrc' # src: Reload .bashrc file
mcd () { mkdir -p "$1" && cd "$1"; } # mcd: Makes new Dir and jumps inside
# lr: Full Recursive Directory Listing
# ------------------------------------------
alias lr='ls -R | grep ":$" | sed -e '\''s/:$//'\'' -e '\''s/[^-][^\/]*\//--/g'\'' -e '\''s/^/ /'\'' -e '\''s/-/|/'\'' | less'
# mans: Search manpage given in agument '1' for term given in argument '2' (case insensitive)
# displays paginated result with colored search terms and two lines surrounding each hit. Example: mans mplayer codec
# --------------------------------------------------------------------
mans () {
man $1 | grep -iC2 --color=always $2 | less
}
# showa: to remind yourself of an alias (given some part of it)
# ------------------------------------------------------------
showa () { /usr/bin/grep --color=always -i -a1 $@ ~/Library/init/bash/aliases.bash | grep -v '^\s*$' | less -FSRXc ; }
# -------------------------------
# 2. FILE AND FOLDER MANAGEMENT
# -------------------------------
zipf () { zip -r "$1".zip "$1" ; } # zipf: To create a ZIP archive of a folder
alias numFiles='echo $(ls -1 | wc -l)' # numFiles: Count of non-hidden files in current dir
alias make1mb='truncate -s 1m ./1MB.dat' # make1mb: Creates a file of 1mb size (all zeros)
alias make5mb='truncate -s 5m ./5MB.dat' # make5mb: Creates a file of 5mb size (all zeros)
alias make10mb='truncate -s 10m ./10MB.dat' # make10mb: Creates a file of 10mb size (all zeros)
# extract: Extract most know archives with one command
# ---------------------------------------------------------
extract () {
if [ -f $1 ] ; then
case $1 in
*.tar.bz2) tar xjf $1 ;;
*.tar.gz) tar xzf $1 ;;
*.bz2) bunzip2 $1 ;;
*.rar) unrar e $1 ;;
*.gz) gunzip $1 ;;
*.tar) tar xf $1 ;;
*.tbz2) tar xjf $1 ;;
*.tgz) tar xzf $1 ;;
*.zip) unzip $1 ;;
*.Z) uncompress $1 ;;
*.7z) 7z x $1 ;;
*) echo "'$1' cannot be extracted via extract()" ;;
esac
else
echo "'$1' is not a valid file"
fi
}
# ---------------------------
# 3. SEARCHING
# ---------------------------
alias qfind="find . -name " # qfind: Quickly search for file
ff () { /usr/bin/find . -name "$@" ; } # ff: Find file under the current directory
ffs () { /usr/bin/find . -name "$@"'*' ; } # ffs: Find file whose name starts with a given string
ffe () { /usr/bin/find . -name '*'"$@" ; } # ffe: Find file whose name ends with a given string
# ---------------------------
# 4. PROCESS MANAGEMENT
# ---------------------------
# findPid: find out the pid of a specified process
# -----------------------------------------------------
# Note that the command name can be specified via a regex
# E.g. findPid '/d$/' finds pids of all processes with names ending in 'd'
# Without the 'sudo' it will only find processes of the current user
# -----------------------------------------------------
findPid () { lsof -t -c "$@" ; }
# memHogsTop, memHogsPs: Find memory hogs
# -----------------------------------------------------
alias memHogsTop='top -l 1 -o rsize | head -20'
alias memHogsPs='ps wwaxm -o pid,stat,vsize,rss,time,command | head -10'
# cpuHogs: Find CPU hogs
# -----------------------------------------------------
alias cpu_hogs='ps wwaxr -o pid,stat,%cpu,time,command | head -10'
# topForever: Continual 'top' listing (every 10 seconds)
# -----------------------------------------------------
alias topForever='top -l 9999999 -s 10 -o cpu'
# ttop: Recommended 'top' invocation to minimize resources
# ------------------------------------------------------------
# Taken from this macosxhints article
# http://www.macosxhints.com/article.php?story=20060816123853639
# ------------------------------------------------------------
alias ttop="top -R -F -s 10 -o rsize"
# my_ps: List processes owned by my user:
# ------------------------------------------------------------
my_ps() { ps $@ -u $USER -o pid,%cpu,%mem,start,time,bsdtime,command ; }
# ---------------------------
# 5. NETWORKING
# ---------------------------
alias myip='curl ifconfig.co' # myip: Public facing IP Address
alias netCons='lsof -i' # netCons: Show all open TCP/IP sockets
alias lsock='sudo /usr/sbin/lsof -i -P' # lsock: Display open sockets
alias lsockU='sudo /usr/sbin/lsof -nP | grep UDP' # lsockU: Display only open UDP sockets
alias lsockT='sudo /usr/sbin/lsof -nP | grep TCP' # lsockT: Display only open TCP sockets
alias ipInfo0='ifconfig getpacket en0' # ipInfo0: Get info on connections for en0
alias ipInfo1='ifconfig getpacket en1' # ipInfo1: Get info on connections for en1
alias openPorts='sudo lsof -i | grep LISTEN' # openPorts: All listening connections
alias showBlocked='sudo ipfw list' # showBlocked: All ipfw rules inc/ blocked IPs
# ii: display useful host related informaton
# -------------------------------------------------------------------
ii() {
echo -e "\nYou are logged on ${red}$HOST"
echo -e "\nAdditionnal information:$NC " ; uname -a
echo -e "\n${red}Users logged on:$NC " ; w -h
echo -e "\n${red}Current date :$NC " ; date
echo -e "\n${red}Machine stats :$NC " ; uptime
#echo -e "\n${red}Current network location :$NC " ; scselect
echo -e "\n${red}Public facing IP Address :$NC " ;myip
#echo -e "\n${red}DNS Configuration:$NC " ; scutil --dns
echo
}
# ---------------------------------------
# 6. SYSTEMS OPERATIONS & INFORMATION
# ---------------------------------------
alias mountReadWrite='/sbin/mount -uw /' # mountReadWrite: For use when booted into single-user
alias perm='stat --printf "%a %n \n "' # perm: Show permission of target in number
alias 000='chmod 000' # ---------- (no fucking permissions)
alias 640='chmod 640' # -rw-r----- (user: rw, group: r, other: -)
alias 644='chmod 644' # -rw-r--r-- (user: rw, group: r, other: -)
alias 755='chmod 755' # -rwxr-xr-x (user: rwx, group: rx, other: x)
alias 775='chmod 775' # -rwxrwxr-x (user: rwx, group: rwx, other: rx)
alias mx='chmod a+x' # ---x--x--x (user: --x, group: --x, other: --x)
alias ux='chmod u+x' # ---x------ (user: --x, group: -, other: -)
# batch_chmod: Batch chmod for all files & sub-directories in the current one
# -------------------------------------------------------------------
batch_chmod()
{
e_header "Restore all files and sub-directories permissions..."
progress 10 "Re-index file list..."
find . -type d -print0 | xargs -0 chmod 0755 && progress 40 "[1/2]"
find . -type f -print0 | xargs -0 chmod 0644 && progress 90 "[2/2]"
progress 100 "Done!"
echo "$(tput sgr0)"
}
# ---------------------------------------
# 7. DATE & TIME MANAGEMENT
# ---------------------------------------
alias bdate="date '+%a, %b %d %Y %T %Z'"
alias cal='cal -3'
alias da='date "+%Y-%m-%d %A %T %Z"'
alias daysleft='echo "There are $(($(date +%j -d"Dec 31, $(date +%Y)")-$(date +%j))) left in year $(date +%Y)."'
alias epochtime='date +%s'
alias mytime='date +%H:%M:%S'
alias secconvert='date -d@1234567890'
alias stamp='date "+%Y%m%d%a%H%M"'
alias timestamp='date "+%Y%m%dT%H%M%S"'
alias today='date +"%A, %B %-d, %Y"'
alias weeknum='date +%V'
# ---------------------------------------
# 8. WEB DEVELOPMENT
# ---------------------------------------
alias apacheEdit='sudo edit /etc/httpd/httpd.conf' # apacheEdit: Edit httpd.conf
alias apacheRestart='sudo apachectl graceful' # apacheRestart: Restart Apache
alias editHosts='sudo edit /etc/hosts' # editHosts: Edit /etc/hosts file
alias herr='tail /var/log/httpd/error_log' # herr: Tails HTTP error logs
alias apacheLogs="less +F /var/log/apache2/error_log" # Apachelogs: Shows apache error logs
httpHeaders () { /usr/bin/curl -I -L $@ ; } # httpHeaders: Grabs headers from web page
# httpDebug: Download a web page and show info on what took time
# -------------------------------------------------------------------
httpDebug () { /usr/bin/curl $@ -o /dev/null -w "dns: %{time_namelookup} connect: %{time_connect} pretransfer: %{time_pretransfer} starttransfer: %{time_starttransfer} total: %{time_total}\n" ; }
# ---------------------------------------
# 9. REMINDERS & NOTES
# ---------------------------------------
# remove_disk: spin down unneeded disk
# ---------------------------------------
# diskutil eject /dev/disk1s3
# to change the password on an encrypted disk image:
# ---------------------------------------
# hdiutil chpass /path/to/the/diskimage
# to mount a read-only disk image as read-write:
# ---------------------------------------
# hdiutil attach example.dmg -shadow /tmp/example.shadow -noverify
# mounting a removable drive (of type msdos or hfs)
# ---------------------------------------
# mkdir /Volumes/Foo
# ls /dev/disk* to find out the device to use in the mount command)
# mount -t msdos /dev/disk1s1 /Volumes/Foo
# mount -t hfs /dev/disk1s1 /Volumes/Foo
# to create a file of a given size: /usr/sbin/mkfile or /usr/bin/hdiutil
# ---------------------------------------
# e.g.: mkfile 10m 10MB.dat
# e.g.: hdiutil create -size 10m 10MB.dmg
# the above create files that are almost all zeros - if random bytes are desired
# then use: ~/Dev/Perl/randBytes 1048576 > 10MB.dat

237
plugins/git/git.plugin.sh Normal file

@ -0,0 +1,237 @@
#
# Functions
#
# The name of the current branch
# Back-compatibility wrapper for when this function was defined here in
# the plugin, before being pulled in to core lib/git.zsh as git_current_branch()
# to fix the core -> git plugin dependency.
function current_branch() {
git_current_branch
}
# The list of remotes
function current_repository() {
if ! $_omb_git_git_cmd rev-parse --is-inside-work-tree &> /dev/null; then
return
fi
echo $($_omb_git_git_cmd remote -v | cut -d':' -f 2)
}
# Pretty log messages
function _git_log_prettily(){
if ! [ -z $1 ]; then
git log --pretty=$1
fi
}
# Warn if the current branch is a WIP
function work_in_progress() {
if $(git log -n 1 2>/dev/null | grep -q -c "\-\-wip\-\-"); then
echo "WIP!!"
fi
}
#
# Aliases
# (sorted alphabetically)
#
alias g='git'
alias ga='git add'
alias gaa='git add --all'
alias gapa='git add --patch'
alias gau='git add --update'
alias gb='git branch'
alias gba='git branch -a'
alias gbd='git branch -d'
alias gbda='git branch --no-color --merged | command grep -vE "^(\*|\s*(master|develop|dev)\s*$)" | command xargs -n 1 git branch -d'
alias gbl='git blame -b -w'
alias gbnm='git branch --no-merged'
alias gbr='git branch --remote'
alias gbs='git bisect'
alias gbsb='git bisect bad'
alias gbsg='git bisect good'
alias gbsr='git bisect reset'
alias gbss='git bisect start'
alias gc='git commit -v'
alias gc!='git commit -v --amend'
alias gcn!='git commit -v --no-edit --amend'
alias gca='git commit -v -a'
alias gca!='git commit -v -a --amend'
alias gcan!='git commit -v -a --no-edit --amend'
alias gcans!='git commit -v -a -s --no-edit --amend'
alias gcam='git commit -a -m'
alias gcsm='git commit -s -m'
alias gcb='git checkout -b'
alias gcf='git config --list'
alias gcl='git clone --recursive'
alias gclean='git clean -fd'
alias gpristine='git reset --hard && git clean -dfx'
alias gcm='git checkout master'
alias gcd='git checkout develop'
alias gcmsg='git commit -m'
alias gco='git checkout'
alias gcount='git shortlog -sn'
compdef _git gcount
alias gcp='git cherry-pick'
alias gcpa='git cherry-pick --abort'
alias gcpc='git cherry-pick --continue'
alias gcs='git commit -S'
alias gd='git diff'
alias gdca='git diff --cached'
alias gdct='git describe --tags `git rev-list --tags --max-count=1`'
alias gdt='git diff-tree --no-commit-id --name-only -r'
alias gdw='git diff --word-diff'
gdv() { git diff -w "$@" | view - }
compdef _git gdv=git-diff
alias gf='git fetch'
alias gfa='git fetch --all --prune'
alias gfo='git fetch origin'
function gfg() { git ls-files | grep $@ }
compdef _grep gfg
alias gg='git gui citool'
alias gga='git gui citool --amend'
ggf() {
[[ "$#" != 1 ]] && local b="$(git_current_branch)"
git push --force origin "${b:=$1}"
}
compdef _git ggf=git-checkout
ggl() {
if [[ "$#" != 0 ]] && [[ "$#" != 1 ]]; then
git pull origin "${*}"
else
[[ "$#" == 0 ]] && local b="$(git_current_branch)"
git pull origin "${b:=$1}"
fi
}
compdef _git ggl=git-checkout
ggp() {
if [[ "$#" != 0 ]] && [[ "$#" != 1 ]]; then
git push origin "${*}"
else
[[ "$#" == 0 ]] && local b="$(git_current_branch)"
git push origin "${b:=$1}"
fi
}
compdef _git ggp=git-checkout
ggpnp() {
if [[ "$#" == 0 ]]; then
ggl && ggp
else
ggl "${*}" && ggp "${*}"
fi
}
compdef _git ggpnp=git-checkout
ggu() {
[[ "$#" != 1 ]] && local b="$(git_current_branch)"
git pull --rebase origin "${b:=$1}"
}
compdef _git ggu=git-checkout
alias ggpur='ggu'
compdef _git ggpur=git-checkout
alias ggpull='git pull origin $(git_current_branch)'
compdef _git ggpull=git-checkout
alias ggpush='git push origin $(git_current_branch)'
compdef _git ggpush=git-checkout
alias ggsup='git branch --set-upstream-to=origin/$(git_current_branch)'
alias gpsup='git push --set-upstream origin $(git_current_branch)'
alias ghh='git help'
alias gignore='git update-index --assume-unchanged'
alias gignored='git ls-files -v | grep "^[[:lower:]]"'
alias git-svn-dcommit-push='git svn dcommit && git push github master:svntrunk'
compdef _git git-svn-dcommit-push=git
alias gk='\gitk --all --branches'
compdef _git gk='gitk'
alias gke='\gitk --all $(git log -g --pretty=%h)'
compdef _git gke='gitk'
alias gl='git pull'
alias glg='git log --stat'
alias glgp='git log --stat -p'
alias glgg='git log --graph'
alias glgga='git log --graph --decorate --all'
alias glgm='git log --graph --max-count=10'
alias glo='git log --oneline --decorate'
alias glol="git log --graph --pretty='%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit"
alias glola="git log --graph --pretty='%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --all"
alias glog='git log --oneline --decorate --graph'
alias gloga='git log --oneline --decorate --graph --all'
alias glp="_git_log_prettily"
compdef _git glp=git-log
alias gm='git merge'
alias gmom='git merge origin/master'
alias gmt='git mergetool --no-prompt'
alias gmtvim='git mergetool --no-prompt --tool=vimdiff'
alias gmum='git merge upstream/master'
alias gp='git push'
alias gpd='git push --dry-run'
alias gpoat='git push origin --all && git push origin --tags'
compdef _git gpoat=git-push
alias gpu='git push upstream'
alias gpv='git push -v'
alias gr='git remote'
alias gra='git remote add'
alias grb='git rebase'
alias grba='git rebase --abort'
alias grbc='git rebase --continue'
alias grbi='git rebase -i'
alias grbm='git rebase master'
alias grbs='git rebase --skip'
alias grh='git reset HEAD'
alias grhh='git reset HEAD --hard'
alias grmv='git remote rename'
alias grrm='git remote remove'
alias grset='git remote set-url'
alias grt='cd $(git rev-parse --show-toplevel || echo ".")'
alias gru='git reset --'
alias grup='git remote update'
alias grv='git remote -v'
alias gsb='git status -sb'
alias gsd='git svn dcommit'
alias gsi='git submodule init'
alias gsps='git show --pretty=short --show-signature'
alias gsr='git svn rebase'
alias gss='git status -s'
alias gst='git status'
alias gsta='git stash save'
alias gstaa='git stash apply'
alias gstc='git stash clear'
alias gstd='git stash drop'
alias gstl='git stash list'
alias gstp='git stash pop'
alias gsts='git stash show --text'
alias gsu='git submodule update'
alias gts='git tag -s'
alias gtv='git tag | sort -V'
alias gunignore='git update-index --no-assume-unchanged'
alias gunwip='git log -n 1 | grep -q -c "\-\-wip\-\-" && git reset HEAD~1'
alias gup='git pull --rebase'
alias gupv='git pull --rebase -v'
alias glum='git pull upstream master'
alias gwch='git whatchanged -p --abbrev-commit --pretty=medium'
alias gwip='git add -A; git rm $(git ls-files --deleted) 2> /dev/null; git commit --no-verify -m "--wip-- [skip ci]"'

@ -0,0 +1,60 @@
#!/bin/bash
############################---Description---###################################
# #
# Summary : Show a progress bar GUI on terminal platform #
# Support : destro.nnt@gmail.com #
# Created date : Aug 12,2014 #
# Latest Modified date : Aug 13,2014 #
# #
################################################################################
############################---Usage---#########################################
# Copy below functions (delay and progress fuctions) into your shell script directly
# Then invoke progress function to show progress bar
# In other way, you could import source indirectly then using. Nothing different
################################################################################
#
# Description : delay executing script
#
function delay()
{
sleep 0.2;
}
#
# Description : print out executing progress
#
CURRENT_PROGRESS=0
function progress()
{
PARAM_PROGRESS=$1;
PARAM_STATUS=$2;
if [ $CURRENT_PROGRESS -le 0 -a $PARAM_PROGRESS -ge 0 ] ; then echo -ne "[..........................] (0%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 5 -a $PARAM_PROGRESS -ge 5 ] ; then echo -ne "[#.........................] (5%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 10 -a $PARAM_PROGRESS -ge 10 ]; then echo -ne "[##........................] (10%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 15 -a $PARAM_PROGRESS -ge 15 ]; then echo -ne "[###.......................] (15%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 20 -a $PARAM_PROGRESS -ge 20 ]; then echo -ne "[####......................] (20%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 25 -a $PARAM_PROGRESS -ge 25 ]; then echo -ne "[#####.....................] (25%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 30 -a $PARAM_PROGRESS -ge 30 ]; then echo -ne "[######....................] (30%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 35 -a $PARAM_PROGRESS -ge 35 ]; then echo -ne "[#######...................] (35%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 40 -a $PARAM_PROGRESS -ge 40 ]; then echo -ne "[########..................] (40%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 45 -a $PARAM_PROGRESS -ge 45 ]; then echo -ne "[#########.................] (45%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 50 -a $PARAM_PROGRESS -ge 50 ]; then echo -ne "[##########................] (50%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 55 -a $PARAM_PROGRESS -ge 55 ]; then echo -ne "[###########...............] (55%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 60 -a $PARAM_PROGRESS -ge 60 ]; then echo -ne "[############..............] (60%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 65 -a $PARAM_PROGRESS -ge 65 ]; then echo -ne "[#############.............] (65%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 70 -a $PARAM_PROGRESS -ge 70 ]; then echo -ne "[###############...........] (70%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 75 -a $PARAM_PROGRESS -ge 75 ]; then echo -ne "[#################.........] (75%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 80 -a $PARAM_PROGRESS -ge 80 ]; then echo -ne "[####################......] (80%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 85 -a $PARAM_PROGRESS -ge 85 ]; then echo -ne "[#######################...] (90%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 90 -a $PARAM_PROGRESS -ge 90 ]; then echo -ne "[##########################] (100%) $PARAM_PHASE \r" ; delay; fi;
if [ $CURRENT_PROGRESS -le 100 -a $PARAM_PROGRESS -ge 100 ];then echo -ne 'Done! \n' ; delay; fi;
CURRENT_PROGRESS=$PARAM_PROGRESS;
}

@ -0,0 +1,84 @@
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-bash installation.
export OSH=$HOME/.oh-my-bash
# Set name of the theme to load. Optionally, if you set this to "random"
# it'll load a random theme each time that oh-my-bash is loaded.
OSH_THEME="powerline"
# Uncomment the following line to use case-sensitive completion.
# CASE_SENSITIVE="true"
# Uncomment the following line to use hyphen-insensitive completion. Case
# sensitive completion must be off. _ and - will be interchangeable.
# HYPHEN_INSENSITIVE="true"
# Uncomment the following line to disable bi-weekly auto-update checks.
# DISABLE_AUTO_UPDATE="true"
# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_OSH_DAYS=13
# Uncomment the following line to disable colors in ls.
# DISABLE_LS_COLORS="true"
# Uncomment the following line to disable auto-setting terminal title.
# DISABLE_AUTO_TITLE="true"
# Uncomment the following line to enable command auto-correction.
# ENABLE_CORRECTION="true"
# Uncomment the following line to display red dots whilst waiting for completion.
# COMPLETION_WAITING_DOTS="true"
# Uncomment the following line if you want to disable marking untracked files
# under VCS as dirty. This makes repository status check for large repositories
# much, much faster.
# DISABLE_UNTRACKED_FILES_DIRTY="true"
# Uncomment the following line if you want to change the command execution time
# stamp shown in the history command output.
# The optional three formats: "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# HIST_STAMPS="mm/dd/yyyy"
# Would you like to use another custom folder than $OSH/custom?
# OSH_CUSTOM=/path/to/new-custom-folder
# Which plugins would you like to load? (plugins can be found in ~/.oh-my-bash/plugins/*)
# Custom plugins may be added to ~/.oh-my-bash/custom/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(core git bashmarks progress)
source $OSH/oh-my-bash.sh
# User configuration
# export MANPATH="/usr/local/man:$MANPATH"
# You may need to manually set your language environment
# export LANG=en_US.UTF-8
# Preferred editor for local and remote sessions
# if [[ -n $SSH_CONNECTION ]]; then
# export EDITOR='vim'
# else
# export EDITOR='mvim'
# fi
# Compilation flags
# export ARCHFLAGS="-arch x86_64"
# ssh
# export SSH_KEY_PATH="~/.ssh/rsa_id"
# Set personal aliases, overriding those provided by oh-my-bash libs,
# plugins, and themes. Aliases can be placed here, though oh-my-bash
# users are encouraged to define aliases within the OSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias bashconfig="mate ~/.bashrc"
# alias ohmybash="mate ~/.oh-my-bash"

110
themes/powerline.theme.sh Normal file

@ -0,0 +1,110 @@
#!/usr/bin/env bash
__nntoan() {
# Unicode symbols
readonly PS_SYMBOL_DARWIN=''
readonly PS_SYMBOL_LINUX='$'
readonly PS_SYMBOL_OTHER='%'
readonly GIT_BRANCH_SYMBOL='⑂ '
readonly GIT_BRANCH_CHANGED_SYMBOL='+'
readonly GIT_NEED_PUSH_SYMBOL='⇡'
readonly GIT_NEED_PULL_SYMBOL='⇣'
# Solarized colorscheme
readonly FG_BASE03="\[$(tput setaf 8)\]"
readonly FG_BASE02="\[$(tput setaf 0)\]"
readonly FG_BASE01="\[$(tput setaf 10)\]"
readonly FG_BASE00="\[$(tput setaf 11)\]"
readonly FG_BASE0="\[$(tput setaf 12)\]"
readonly FG_BASE1="\[$(tput setaf 14)\]"
readonly FG_BASE2="\[$(tput setaf 7)\]"
readonly FG_BASE3="\[$(tput setaf 15)\]"
readonly BG_BASE03="\[$(tput setab 8)\]"
readonly BG_BASE02="\[$(tput setab 0)\]"
readonly BG_BASE01="\[$(tput setab 10)\]"
readonly BG_BASE00="\[$(tput setab 11)\]"
readonly BG_BASE0="\[$(tput setab 12)\]"
readonly BG_BASE1="\[$(tput setab 14)\]"
readonly BG_BASE2="\[$(tput setab 7)\]"
readonly BG_BASE3="\[$(tput setab 15)\]"
readonly FG_YELLOW="\[$(tput setaf 3)\]"
readonly FG_ORANGE="\[$(tput setaf 9)\]"
readonly FG_RED="\[$(tput setaf 1)\]"
readonly FG_MAGENTA="\[$(tput setaf 5)\]"
readonly FG_VIOLET="\[$(tput setaf 13)\]"
readonly FG_BLUE="\[$(tput setaf 4)\]"
readonly FG_CYAN="\[$(tput setaf 6)\]"
readonly FG_GREEN="\[$(tput setaf 2)\]"
readonly BG_YELLOW="\[$(tput setab 3)\]"
readonly BG_ORANGE="\[$(tput setab 9)\]"
readonly BG_RED="\[$(tput setab 1)\]"
readonly BG_MAGENTA="\[$(tput setab 5)\]"
readonly BG_VIOLET="\[$(tput setab 13)\]"
readonly BG_BLUE="\[$(tput setab 4)\]"
readonly BG_CYAN="\[$(tput setab 6)\]"
readonly BG_GREEN="\[$(tput setab 2)\]"
readonly DIM="\[$(tput dim)\]"
readonly REVERSE="\[$(tput rev)\]"
readonly RESET="\[$(tput sgr0)\]"
readonly BOLD="\[$(tput bold)\]"
# what OS?
case "$(uname)" in
Darwin)
readonly PS_SYMBOL=$PS_SYMBOL_DARWIN
;;
Linux)
readonly PS_SYMBOL=$PS_SYMBOL_LINUX
;;
*)
readonly PS_SYMBOL=$PS_SYMBOL_OTHER
esac
__git_info() {
[ -x "$(which git)" ] || return # git not found
local git_eng="env LANG=C git" # force git output in English to make our work easier
# get current branch name or short SHA1 hash for detached head
local branch="$($git_eng symbolic-ref --short HEAD 2>/dev/null || $git_eng describe --tags --always 2>/dev/null)"
[ -n "$branch" ] || return # git branch not found
local marks
# branch is modified?
[ -n "$($git_eng status --porcelain)" ] && marks+=" $GIT_BRANCH_CHANGED_SYMBOL"
# how many commits local branch is ahead/behind of remote?
local stat="$($git_eng status --porcelain --branch | grep '^##' | grep -o '\[.\+\]$')"
local aheadN="$(echo $stat | grep -o 'ahead [[:digit:]]\+' | grep -o '[[:digit:]]\+')"
local behindN="$(echo $stat | grep -o 'behind [[:digit:]]\+' | grep -o '[[:digit:]]\+')"
[ -n "$aheadN" ] && marks+=" $GIT_NEED_PUSH_SYMBOL$aheadN"
[ -n "$behindN" ] && marks+=" $GIT_NEED_PULL_SYMBOL$behindN"
# print the git branch segment without a trailing newline
printf " $GIT_BRANCH_SYMBOL$branch$marks "
}
ps1() {
# Check the exit code of the previous command and display different
# colors in the prompt accordingly.
if [ $? -eq 0 ]; then
local BG_EXIT="$BG_GREEN"
else
local BG_EXIT="$BG_RED"
fi
PS1="$BG_BASE1$FG_BASE3 \w $RESET"
PS1+="$BG_BLUE$FG_BASE3$(__git_info)$RESET"
PS1+="$BG_EXIT$FG_BASE3 $PS_SYMBOL $RESET "
}
PROMPT_COMMAND=ps1
}
__nntoan
unset __nntoan

@ -0,0 +1,60 @@
#!/usr/bin/env bash
EPOCHSECONDS="$(date +%s)"
function _current_epoch() {
echo $(( $EPOCHSECONDS / 60 / 60 / 24 ))
}
function _update_osh_update() {
echo "LAST_EPOCH=$(_current_epoch)" >! ~/.osh-update
}
function _upgrade_osh() {
env OSH=$OSH sh $OSH/tools/upgrade.sh
# update the osh file
_update_osh_update
}
epoch_target=$UPDATE_OSH_DAYS
if [[ -z "$epoch_target" ]]; then
# Default to old behavior
epoch_target=13
fi
# Cancel upgrade if the current user doesn't have write permissions for the
# oh-my-bash directory.
[[ -w "$OSH" ]] || return 0
# Cancel upgrade if git is unavailable on the system
which git >/dev/null || return 0
if mkdir "$OSH/log/update.lock" 2>/dev/null; then
if [ -f ~/.osh-update ]; then
. ~/.osh-update
if [[ -z "$LAST_EPOCH" ]]; then
_update_osh_update && return 0;
fi
epoch_diff=$(($(_current_epoch) - $LAST_EPOCH))
if [ $epoch_diff -gt $epoch_target ]; then
if [ "$DISABLE_UPDATE_PROMPT" = "true" ]; then
_upgrade_osh
else
echo "[Oh My Zsh] Would you like to check for updates? [Y/n]: \c"
read line
if [[ "$line" == Y* ]] || [[ "$line" == y* ]] || [ -z "$line" ]; then
_upgrade_osh
else
_update_osh_update
fi
fi
fi
else
# create the osh file
_update_osh_update
fi
rmdir $OSH/log/update.lock
fi

92
tools/install.sh Executable file

@ -0,0 +1,92 @@
#!/usr/bin/env bash
main() {
# Use colors, but only if connected to a terminal, and that terminal
# supports them.
if which tput >/dev/null 2>&1; then
ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
BLUE="$(tput setaf 4)"
BOLD="$(tput bold)"
NORMAL="$(tput sgr0)"
else
RED=""
GREEN=""
YELLOW=""
BLUE=""
BOLD=""
NORMAL=""
fi
# Only enable exit-on-error after the non-critical colorization stuff,
# which may fail on systems lacking tput or terminfo
set -e
if [ ! -n "$OSH" ]; then
OSH=$HOME/.oh-my-bash
fi
if [ -d "$OSH" ]; then
printf "${YELLOW}You already have Oh My Bash installed.${NORMAL}\n"
printf "You'll need to remove $OSH if you want to re-install.\n"
exit
fi
# Prevent the cloned repository from having insecure permissions. Failing to do
# so causes compinit() calls to fail with "command not found: compdef" errors
# for users with insecure umasks (e.g., "002", allowing group writability). Note
# that this will be ignored under Cygwin by default, as Windows ACLs take
# precedence over umasks except for filesystems mounted with option "noacl".
umask g-w,o-w
printf "${BLUE}Cloning Oh My Bash...${NORMAL}\n"
hash git >/dev/null 2>&1 || {
echo "Error: git is not installed"
exit 1
}
# The Windows (MSYS) Git is not compatible with normal use on cygwin
if [ "$OSTYPE" = cygwin ]; then
if git --version | grep msysgit > /dev/null; then
echo "Error: Windows/MSYS Git is not supported on Cygwin"
echo "Error: Make sure the Cygwin git package is installed and is first on the path"
exit 1
fi
fi
env git clone --depth=1 https://github.com/nntoan/oh-my-bash.git $OSH || {
printf "Error: git clone of oh-my-bash repo failed\n"
exit 1
}
printf "${BLUE}Looking for an existing bash config...${NORMAL}\n"
if [ -f ~/.bashrc ] || [ -h ~/.bashrc ]; then
printf "${YELLOW}Found ~/.bashrc.${NORMAL} ${GREEN}Backing up to ~/.bashrc.pre-oh-my-bash${NORMAL}\n";
mv ~/.bashrc ~/.bashrc.pre-oh-my-bash;
fi
printf "${BLUE}Using the Oh My Bash template file and adding it to ~/.bashrc${NORMAL}\n"
cp $OSH/templates/bashrc.osh-template ~/.bashrc
sed "/^export OSH=/ c\\
export OSH=$OSH
" ~/.bashrc > ~/.bashrc-ombtemp
mv -f ~/.bashrc-ombtemp ~/.bashrc
# MOTD message :)
printf '%s' "$GREEN"
printf '%s\n' ' __ __ __ '
printf '%s\n' ' ____ / /_ ____ ___ __ __ / /_ ____ ______/ /_ '
printf '%s\n' ' / __ \/ __ \ / __ `__ \/ / / / / __ \/ __ `/ ___/ __ \'
printf '%s\n' '/ /_/ / / / / / / / / / / /_/ / / /_/ / /_/ (__ ) / / /'
printf '%s\n' '\____/_/ /_/ /_/ /_/ /_/\__, / /_.___/\__,_/____/_/ /_/ '
printf '%s\n' ' /____/ .... is now installed!'
printf "%s\n" "Please look over the ~/.bashrc file to select plugins, themes, and options"
printf "${BLUE}${BOLD}%s${NORMAL}\n" "To keep up on the latest news and updates, follow us on GitHub: https://github.com/nntoan/oh-my-bash"
source $HOME/.bashrc
env bash
}
main

36
tools/uninstall.sh Normal file

@ -0,0 +1,36 @@
#!/usr/bin/env bash
read -r -p "Are you sure you want to remove Oh My Bash? [y/N] " confirmation
if [ "$confirmation" != y ] && [ "$confirmation" != Y ]; then
echo "Uninstall cancelled"
exit
fi
echo "Removing ~/.oh-my-bash"
if [ -d ~/.oh-my-bash ]; then
rm -rf ~/.oh-my-bash
fi
echo "Looking for original bash config..."
if [ -f ~/.bashrc.pre-oh-my-bash ] || [ -h ~/.bashrc.pre-oh-my-bash ]; then
echo "Found ~/.bashrc.pre-oh-my-bash -- Restoring to ~/.bashrc";
if [ -f ~/.bashrc ] || [ -h ~/.bashrc ]; then
BASHRC_SAVE=".bashrc.omb-uninstalled-$(date +%Y%m%d%H%M%S)";
echo "Found ~/.bashrc -- Renaming to ~/${BASHRC_SAVE}";
mv ~/.bashrc ~/"${BASHRC_SAVE}";
fi
mv ~/.bashrc.pre-oh-my-bash ~/.bashrc;
echo "Your original bash config was restored. Please restart your session."
else
if hash chsh >/dev/null 2>&1; then
echo "Switching back to bash"
chsh -s /bin/bash
else
echo "You can edit /etc/passwd to switch your default shell back to bash"
fi
fi
echo "Thanks for trying out Oh My Bash. It's been uninstalled."

37
tools/upgrade.sh Normal file

@ -0,0 +1,37 @@
# Use colors, but only if connected to a terminal, and that terminal
# supports them.
if which tput >/dev/null 2>&1; then
ncolors=$(tput colors)
fi
if [ -t 1 ] && [ -n "$ncolors" ] && [ "$ncolors" -ge 8 ]; then
RED="$(tput setaf 1)"
GREEN="$(tput setaf 2)"
YELLOW="$(tput setaf 3)"
BLUE="$(tput setaf 4)"
BOLD="$(tput bold)"
NORMAL="$(tput sgr0)"
else
RED=""
GREEN=""
YELLOW=""
BLUE=""
BOLD=""
NORMAL=""
fi
printf "${BLUE}%s${NORMAL}\n" "Updating Oh My Bash"
cd "$OSH"
if git pull --rebase --stat origin master
then
printf '%s' "$GREEN"
printf '%s\n' ' __ __ __ '
printf '%s\n' ' ____ / /_ ____ ___ __ __ / /_ ____ ______/ /_ '
printf '%s\n' ' / __ \/ __ \ / __ `__ \/ / / / / __ \/ __ `/ ___/ __ \'
printf '%s\n' '/ /_/ / / / / / / / / / / /_/ / / /_/ / /_/ (__ ) / / /'
printf '%s\n' '\____/_/ /_/ /_/ /_/ /_/\__, / /_.___/\__,_/____/_/ /_/ '
printf '%s\n' ' /____/ '
printf "${BLUE}%s\n" "Hooray! Oh My Bash has been updated and/or is at the current version."
printf "${BLUE}${BOLD}%s${NORMAL}\n" "To keep up on the latest news and updates, follow us on GitHub: https://github.com/nntoan/oh-my-bash"
else
printf "${RED}%s${NORMAL}\n" 'There was an error updating. Try again later?'
fi