Skip to content

Instantly share code, notes, and snippets.

@AlexRNL
Created March 16, 2020 14:07
Show Gist options
  • Save AlexRNL/9f5d77ed1a7567320e08cec901b0656e to your computer and use it in GitHub Desktop.
Save AlexRNL/9f5d77ed1a7567320e08cec901b0656e to your computer and use it in GitHub Desktop.
bash configuration files
#!/bin/bash
# Aliases definition file
# -----------------------
# Enable color support of ls, grep, ip, etc.
aliases_color () {
if [[ -x /usr/bin/dircolors ]] ; then
local dircolors_file=""
if [[ -r ~/.dircolors ]] ; then
dircolors_file=~/.dircolors
fi
dircolors --bourne-shell ${dircolors_file} >/dev/null 2>&1
alias ls='ls --color=auto'
alias dir='dir --color=auto'
alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias ip='ip --color'
fi
}
# Define classic aliases (ls, cd, mv, rm, etc.)
aliases_classic () {
# Handy ls aliases
alias ll='ls --format long'
alias la='ls --almost-all'
alias l='ls --classify --format vertical'
# Avoid overwriting existing files
alias cp='cp --interactive'
alias mv='mv --interactive'
}
# Define aliases for chroots
aliases_chroot () {
# jessie64
alias jessie64='schroot --chroot jessie64 --preserve-environment --'
alias root_jessie64='schroot --user root --chroot jessie64 --preserve-environment --'
# stretch64
alias stretch64='schroot --chroot stretch64 --preserve-environment --'
alias root_stretch64='schroot --user root --chroot stretch64 --preserve-environment --'
# buster64
alias buster64='schroot --chroot buster64 --preserve-environment --'
alias root_buster64='schroot --user root --chroot buster64 --preserve-environment --'
}
# Function that add an alias to the file if it exists with the following parameters
# * file to check
# * alias to add
# * command to alias (if not defined, uses the file)
aliases_check_add () {
local file=${1}
local alias=${2}
local cmd=${3:-$file}
if [[ -e ${file} ]] ; then
# shellcheck disable=SC2139
alias "${alias}"="${cmd}"
fi
}
# Main function
aliases_main () {
if [[ -n ${_BASH_ALIASES_:-""} ]] ; then
return
fi
export _BASH_ALIASES_="bash_aliases loaded"
aliases_color
aliases_classic
aliases_chroot
aliases_check_add ~/bin/nvim.appimage nvim
aliases_check_add ~/bin/yed-3.18.2/yed.jar yed 'java -jar ~/bin/yed-3.18.2/yed.jar'
# shellcheck disable=SC2016
aliases_check_add /dev/null path 'printf "%s\n" "${PATH//:/
}"'
aliases_check_add /dev/null which 'type -a'
}
aliases_main "${@}"
# shellcheck disable=SC2148
# ~/.bashrc: executed by bash(1) for non-login shells.
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
# for examples
# If not running interactively, don't do anything
case $- in
*i*) ;;
*) return;;
esac
#=====================================================#
# Main initializations #
#=====================================================#
# Add customs script directory to path
if [[ -d "$HOME/Documents/scripts" ]] ; then
PATH="$PATH:$HOME/Documents/scripts"
fi
# Set CDPATH to change dir more efficiently
CDPATH=".:~"
if [[ -d "${HOME}/workspace" ]] ; then
CDPATH="${CDPATH}:~/workspace"
fi
export CDPATH
# Set variable identifying the chroot you work in (used in the prompt)
if [[ -z "${debian_chroot:-}"
&& -r /etc/debian_chroot ]] ; then
debian_chroot=$(cat /etc/debian_chroot)
fi
# Alias definitions.
if [[ -f ~/Documents/etc/bash_aliases ]] ; then
# shellcheck source=/home/alex/Documents/etc/bash_aliases
source "${HOME}/Documents/etc/bash_aliases"
fi
# enable programmable completion features (you don't need to enable
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
# sources /etc/bash.bashrc).
if ! shopt -oq posix; then
if [[ -f /usr/share/bash-completion/bash_completion ]] ; then
source "/usr/share/bash-completion/bash_completion"
elif [[ -f /etc/bash_completion ]] ; then
source "/etc/bash_completion"
fi
fi
#=====================================================#
# Colors configuration #
#=====================================================#
# set a fancy prompt (non-color, unless we know we "want" color)
case "${TERM}" in
xterm-color|*-256color) color_prompt=yes;;
esac
# uncomment for a colored prompt, if the terminal has the capability; turned
# off by default to not distract the user: the focus in a terminal window
# should be on the output of commands, not on the prompt
force_color_prompt=yes
if [[ -n "${force_color_prompt}" ]] ; then
if [[ -x /usr/bin/tput ]] && tput setaf 1 >&/dev/null; then
# We have color support; assume it's compliant with Ecma-48
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
# a case would tend to support setf rather than setaf.)
color_prompt=yes
else
color_prompt=
fi
fi
# Color definitions.
if [[ -f "${HOME}/Documents/etc/bash_colors" ]] ; then
# shellcheck source=/home/alex/Documents/etc/bash_colors
source "${HOME}/Documents/etc/bash_colors"
fi
# Set shell prompt
if [[ "$color_prompt" = yes ]] ; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
else
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
fi
unset color_prompt force_color_prompt
# Set GCC option to color output
export GCC_COLORS='error=01;31:warning=01;33:note=01;34:caret=05;32:locus=0;32:quote=0;92'
# Custom colors for grep
export GREP_COLORS='1;34'
# Enable colored logs (in common.sh script)
export COLORED_LOGS='true'
# Enable colored man
man() {
env LESS_TERMCAP_mb=$'\E[01;31m' \
LESS_TERMCAP_md=$'\E[01;38;5;74m' \
LESS_TERMCAP_me=$'\E[0m' \
LESS_TERMCAP_se=$'\E[0m' \
LESS_TERMCAP_so=$'\E[38;5;11m' \
LESS_TERMCAP_ue=$'\E[0m' \
LESS_TERMCAP_us=$'\E[04;38;5;146m' \
man "${@}"
}
#=====================================================#
# Network configuration #
#=====================================================#
# Start ssh-agent if needed
if hash ssh-agent-start.sh 2>/dev/null ; then
# shellcheck source=/home/alex/Documents/scripts/ssh-agent-start.sh
source ssh-agent-start.sh
fi
# Add SSH key if missing
if [[ $(ssh-add -l | grep --count "${HOME}/.ssh") -eq 0 ]] ; then
ssh-add
fi
# Start a tunnel to Jenkins only if no process is already listening to the specified port
start_ssh_tunnel () {
# ss option --no-header is not avaible is the version packaged for Jessie
if [[ $(ss --tcp --listening --processes --numeric "sport eq :${1}" | grep --invert-match --extended-regexp "^State") == "" ]] ; then
ssh -4 -NL ${1}:localhost:${1} -f devc@jenkins-devc
fi
}
# Start ssh tunnels to Jenkins agents only on main machine
if [[ $(hostname) != "dell-b4nhz42" ]] ; then
# Jessie
start_ssh_tunnel "9306"
# Stretch
start_ssh_tunnel "9308"
# Buster
start_ssh_tunnel "9310"
fi
#=====================================================#
# Shell configuration options #
#=====================================================#
# check the window size after each command and, if necessary, update the values of LINES and COLUMNS.
shopt -s checkwinsize
# If set, the pattern "**" used in a pathname expansion context will match all files and zero or more directories and subdirectories.
#shopt -s globstar
# make less more friendly for non-text input files, see lesspipe(1)
#[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
# Check there are no running jobs before exit
shopt -s checkjobs
# Avoid redirection which would overwrite existing files
set -o noclobber
# Correct (minor) errors in directories names
shopt -s cdspell
# Avoid offering completion when nothing has been typed
shopt -s no_empty_cmd_completion
# Avoid checking emails
unset MAILCHECK
# avoid execution of copy-paste blocks of code
bind "set enable-bracketed-paste on"
# by default, readline will autocomplete with the first choice
# show-all-if-ambiguous will not autocomplete, juste show a list of possibilities
# show-all-if-unmodified permits to autocomplete common parts, and show a list of possiblities
bind "set show-all-if-unmodified on"
# Be more intelligent when autocompleting by also looking at the text after
# the cursor. For example, when the current line is "cd ~/src/mozil", and
# the cursor is on the "z", pressing Tab will not autocomplete it to "cd
# ~/src/mozillail", but to "cd ~/src/mozilla". (This is supported by the
# Readline used by Bash 4.)
bind "set skip-completed-text on"
# ignore case with completion, once you taste it, you can't go without it
bind "set completion-ignore-case on"
# Treat hyphens and underscores as equivalent for completion
bind "set completion-map-case on"
# add a character after the file name in completion list (like ls -F)
bind "set visible-stats on"
# Function called when command is not found
command_not_found_handle() {
local cmd="${1}"
shift
local full_cmd
# If command starts with git
if hash git 2>/dev/null && [[ "git" == "${cmd:0:3}" ]] ; then
full_cmd="git ${cmd:3} ${*}"
fi
# If command is gti
if hash git 2>/dev/null && [[ "gti" == "${cmd}" ]] ; then
full_cmd="git ${*}"
fi
# If full_cmd is defined, the command has been fixed
if [[ -n "${full_cmd}" ]] ; then
printf "Fix last call to (%bCTRL+C%b to abort): %b%s%b\n" "${Color_Cyan}" "${Color_Reset}" "${Color_BYellow}" "${full_cmd}" "${Color_Reset}"
sleep 2
${full_cmd}
return $?
else
printf "%b%s%b command not found\n" "${Color_BRed}" "${cmd}" "${Color_Reset}"
return 127
fi
}
#=====================================================#
# History configuration #
#=====================================================#
# append to the history file, don't overwrite it
shopt -s histappend
# don't put duplicate lines or lines starting with space in the history.
# See bash(1) for more options
HISTCONTROL=ignoreboth
# Do not record some commands
HISTIGNORE="bg:fg:ll:ls:exit"
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
HISTSIZE=10000
HISTFILESIZE=50000
# Show date & time in history command
HISTTIMEFORMAT='%F %T '
#=====================================================#
# Miscellaneous #
#=====================================================#
# Use neovim as an editor
if [[ -x ~/bin/nvim.appimage ]] ; then
VISUAL="${HOME}/bin/nvim.appimage"
else
VISUAL="vim"
fi
EDITOR="${VISUAL}"
# Modify PS1 in git folders
if [[ -x ~/bin/bash-git-prompt/gitprompt.sh ]] ; then
export GIT_PROMPT_ONLY_IN_REPO=1
export GIT_PROMPT_THEME="Single_line_Dark"
# Callback that displays chroot
function prompt_callback {
printf "%s" "${debian_chroot:+ ${BoldBlack}$debian_chroot${ResetColor}}"
}
# shellcheck source=/home/alex/bin/bash-git-prompt/gitprompt.sh
source "${HOME}/bin/bash-git-prompt/gitprompt.sh"
fi
# Follow source script with ShellCheck by default
export SHELLCHECK_OPTS="--external-sources"
# Show duration of last command (incompatible with git prompt status ...)
#source ~/bin/bash-command-timer/bash_command_timer.sh
#BCT_ENABLE=1
#BCT_COLOR='94'
#=====================================================#
# Useful functions #
#=====================================================#
# Find a file by a part of its name
find_by_name () {
find . -type f -iname '*'"${*}"'*'
}
# Find a file by a part of its name and highlight the match
ff () {
local old_ifs=${IFS}
IFS="
"
local files
files=( $(find_by_name "${*}") )
ll "${files[@]}" | grep --ignore-case "${1}";
IFS=${old_ifs}
}
# Open matching files in nvim tabs
fo () {
local old_ifs=${IFS}
IFS="
"
local files
files=( $(find_by_name "${*}") )
$EDITOR -O "${files[@]}"
IFS=${old_ifs}
}
# Extract an archive
extract () {
if [[ -f "${1}" ]] ; then
case "${1}" in
*.tar.gz |\
*.tgz) tar --extract --verbose --gzip --file "${1}";;
*.tar.bz2 |\
*.tbz2) tar --extract --verbose --bzip2 --file "${1}";;
*.bz2) bunzip2 "${1}";;
*.gz) gunzip "${1}";;
*.tar.xz) tar --extract --verbose --xz --file "${1}";;
*.xy) xz -d "${1}";;
*.tar) tar --extract --verbose --file "${1}";;
*.Z) uncompress "${1}";;
*.zip) unzip "${1}";;
*.7z) 7z x "${1}";;
*) printf "%b%s%b file format is not known\n" "${Color_BRed}" "${1}" "${Color_Reset}";;
esac
else
printf "%b%s%b is not a valid file\n" "${Color_BRed}" "${1}" "${Color_Reset}"
fi
}
# Connect to postgres on localhost
psql_localhost () {
psql --username postgres --host 127.0.0.1 "${1}"
}
db_ib () {
psql_localhost ib_proorder
}
db_prt () {
psql_localhost papertrading_proorder
}
# Find a process by its name
psgrep () {
# shellcheck disable=SC2009
ps aux | grep --invert-match grep | grep "${@}"
}
# (soft) Delete of a local branch and its remote counterpart
git-branchd () {
git branch --delete "${1}" && git push origin :"${1}"
}
# Display current folder files/folder by size
lsb () {
find "${1:-"."}" -mindepth 1 -maxdepth 1 -exec du --summarize --human-readable '{}' + | sort --human-numeric-sort --reverse
}
## Shortcut functions/aliases to remote-session script
# Calls the script with the 1st argument as the server
s () {
remote-session.sh -s "${1}"
}
# Calls the script with the 1st argument as the server and offer to choose the account to use
t () {
remote-session.sh -ts "${1}"
}
# Calls the script with the account set to proorder and the 1st argument as the server
o () {
remote-session.sh -a "proorder" -s "${1}"
}
# Calls the script with the account set to proinvest and the 1st argument as the server
i () {
remote-session.sh -a "proinvest" -s "${1}"
}
# Calls the script with the account set to devc and the 1st argument as the server
c () {
remote-session.sh -a "devc" -s "${1}"
}
# Calls the script by spliting the 1st argument around the '@'
sshs () {
remote-session.sh -a "${1%%@*}" -s "${1##*@}"
}
# shellcheck disable=SC2148
# bash resource file used on remote servers
###############
# Aliases #
###############
# Enable color support of ls, grep, ip, etc.
aliases_color () {
if [[ -x /usr/bin/dircolors ]] ; then
local dircolors_file=""
if [[ -r ~/.dircolors ]] ; then
dircolors_file=~/.dircolors
fi
dircolors --bourne-shell ${dircolors_file} >/dev/null 2>&1
alias ls='ls --color=auto'
alias dir='dir --color=auto'
alias vdir='vdir --color=auto'
alias grep='grep --color=auto'
alias fgrep='fgrep --color=auto'
alias egrep='egrep --color=auto'
alias ip='ip --color'
fi
}
# Define classic aliases (ls, cd, mv, rm, etc.)
aliases_classic () {
# Handy ls aliases
alias ll='ls --format long'
alias la='ls --almost-all'
alias l='ls --classify --format vertical'
# Avoid overwriting existing files
alias cp='cp --interactive'
alias mv='mv --interactive'
alias which='type -a'
alias path='printf "%s\n" "${PATH//:/
}"'
}
#######################################################
# Shell configuration options #
#######################################################
# check the window size after each command and, if necessary, update the values of LINES and COLUMNS.
shopt -s checkwinsize
# Check there are no running jobs before exit
shopt -s checkjobs
# Avoid redirection which would overwrite existing files
set -o noclobber
# Correct (minor) errors in directories names
shopt -s cdspell
# Avoid offering completion when nothing has been typed
shopt -s no_empty_cmd_completion
# Avoid checking emails
unset MAILCHECK
# avoid execution of copy-paste blocks of code
bind "set enable-bracketed-paste on"
# by default, readline will autocomplete with the first choice
# show-all-if-ambiguous will not autocomplete, juste show a list of possibilities
# show-all-if-unmodified permits to autocomplete common parts, and show a list of possiblities
bind "set show-all-if-unmodified on"
# Be more intelligent when autocompleting by also looking at the text after
# the cursor. For example, when the current line is "cd ~/src/mozil", and
# the cursor is on the "z", pressing Tab will not autocomplete it to "cd
# ~/src/mozillail", but to "cd ~/src/mozilla". (This is supported by the
# Readline used by Bash 4.)
bind "set skip-completed-text on"
# ignore case with completion, once you taste it, you can't go without it
bind "set completion-ignore-case on"
# Treat hyphens and underscores as equivalent for completion
bind "set completion-map-case on"
# add a character after the file name in completion list (like ls -F)
bind "set visible-stats on"
# Main function, define useful aliases and environment variables
main_bashrc_remote () {
# Call regular resource files
source /etc/profile
if [[ -f ~/.bashrc ]] ; then
# shellcheck disable=SC1090
source ~/.bashrc
fi
aliases_color
aliases_classic
# Custom colors for grep
export GREP_COLORS='1;34'
}
# Call main function
main_bashrc_remote
#######################
# Useful functions #
#######################
# Enable colored man
man () {
env LESS_TERMCAP_mb=$'\E[01;31m' \
LESS_TERMCAP_md=$'\E[01;38;5;74m' \
LESS_TERMCAP_me=$'\E[0m' \
LESS_TERMCAP_se=$'\E[0m' \
LESS_TERMCAP_so=$'\E[38;5;11m' \
LESS_TERMCAP_ue=$'\E[0m' \
LESS_TERMCAP_us=$'\E[04;38;5;146m' \
man "${@}"
}
# Find a file by a part of its name
ff () {
find . -type f -iname '*'"${*}"'*' -ls | grep --ignore-case "${1}";
}
# Find a process by its name
psgrep () {
# shellcheck disable=SC2009
ps aux | grep --invert-match grep | grep "${@}"
}
## DB
psql_ ()
{
local conf="${1}" # mandatory conf file
local location="${2}" # mandatory [ ROOT / CHILD ]
local name="${3:-*[1]}" # optional, name of the environment
local has_child
# Show config if name provided is help option
if [[ ${name} == "-h" ||
${name} == "--help" ]] ; then
cat "${conf}"
else
if [[ "${location}" == "ROOT" ]] ; then
has_child="";
elif [[ "${location}" == "CHILD" ]] ; then
has_child="/*[1]";
fi
local psql_args
psql_args=( $(xmlstarlet sel --text --template --match /databases/"${name}""${has_child}" --value-of "concat('-h ', @host, ' -p ', @port, ' ', @name)" "${conf}") )
psql "${psql_args[@]}"
fi
}
# quotes database
psqlq () { psql_ /etc/itf/db/prod/quotes.conf "ROOT" "${1}"; }
# proorder database
psqlt () { psql_ /etc/itf/db/prod/proorder.conf "ROOT" "${1}"; }
# profile database
psqlu () { psql_ /etc/itf/db/prod/profiles.conf "CHILD" "${1}"; }
## GDB utilities
# Display the backtrace of the specified core file (1st argument), if a 2nd argument is present, execute gdb as specified user
bt_usr () {
local core=${1:-""}
local user
user=${2:+"sudo -u ${2}"}
if [[ -z ${core} ]] ; then
printf "Missing core file to analyse\n"
return 1
fi
bin=$(${user} gdb --quiet --eval-command 'q' --core "${core}" |
grep "Core was generated by " |
sed --regexp-extended --expression 's|^Core was generated by .([^ ]+).*$|\1|g')
if [[ ! -f ${bin} ]] ; then
printf "Could not find binary file that generated %s%s\n" "${core}" "${bin:+" (found ${bin})"}"
# Attempt to fix too long strategy folders
local regexp_strat_bin="/autotrading/logs/strategies/archives/([A-Z0-9]+_[0-9]+)/.*'.$"
if [[ ${bin} =~ ${regexp_strat_bin} ]] ; then
bin="${bin%/*}/${BASH_REMATCH[1]}.bin"
if [[ ! -f ${bin} ]] ; then
printf "Could not find strategy binary\n"
return 2
else
printf "Attempt to fix search of strategy binary by using %s\n" "${bin}"
fi
else
return 2
fi
fi
core=$(realpath "${core}")
if ! cd "${bin%/*}" ; then
printf "Could not go into %s\n" "${bin%/*}"
fi
${user} gdb --quiet --eval-command 'bt' --eval-command 'q' "${bin}" "${core}" |
grep --invert-match --extended-regexp "^\[New LWP .*\]$"
if ! cd - ; then
printf "Could return to original directory\n"
fi
return 0
}
# Find to whom the core belongs to before calling bt_usr
bt () {
local user
user=$(stat --format '%U' "${1}")
if [[ ${user} == $(whoami) ]] ; then
user=""
fi
bt_usr "${1}" "${user}"
}
# Calls bt function with pbr user
bt_pbr () {
bt_usr "${1}" pbr
}
# shellcheck disable=SC2148
# bash-colors.sh
# --------------
# Declare bash constant variables for modifying easily shell output
colors_regular () {
# Reset flags
declare -grx Color_Reset='\e[0m' # Text Reset
declare -grx Color_Default=${Color_Reset} # Default color
# Regular Colors
declare -grx Color_Black='\e[0;30m' # Black
declare -grx Color_Red='\e[0;31m' # Red
declare -grx Color_Green='\e[0;32m' # Green
declare -grx Color_Yellow='\e[0;33m' # Yellow
declare -grx Color_Blue='\e[0;34m' # Blue
declare -grx Color_Purple='\e[0;35m' # Purple
declare -grx Color_Cyan='\e[0;36m' # Cyan
declare -grx Color_White='\e[0;37m' # White
}
# Bold
colors_bold () {
declare -grx Color_BBlack='\e[1;30m' # Black
declare -grx Color_BRed='\e[1;31m' # Red
declare -grx Color_BGreen='\e[1;32m' # Green
declare -grx Color_BYellow='\e[1;33m' # Yellow
declare -grx Color_BBlue='\e[1;34m' # Blue
declare -grx Color_BPurple='\e[1;35m' # Purple
declare -grx Color_BCyan='\e[1;36m' # Cyan
declare -grx Color_BWhite='\e[1;37m' # White
}
# Underline
colors_underline () {
declare -grx Color_UBlack='\e[4;30m' # Black
declare -grx Color_URed='\e[4;31m' # Red
declare -grx Color_UGreen='\e[4;32m' # Green
declare -grx Color_UYellow='\e[4;33m' # Yellow
declare -grx Color_UBlue='\e[4;34m' # Blue
declare -grx Color_UPurple='\e[4;35m' # Purple
declare -grx Color_UCyan='\e[4;36m' # Cyan
declare -grx Color_UWhite='\e[4;37m' # White
}
# Background
colors_background () {
declare -grx Color_On_Black='\e[40m' # Black
declare -grx Color_On_Red='\e[41m' # Red
declare -grx Color_On_Green='\e[42m' # Green
declare -grx Color_On_Yellow='\e[43m' # Yellow
declare -grx Color_On_Blue='\e[44m' # Blue
declare -grx Color_On_Purple='\e[45m' # Purple
declare -grx Color_On_Cyan='\e[46m' # Cyan
declare -grx Color_On_White='\e[47m' # White
}
# High Intensity
colors_high_intensity () {
declare -grx Color_IBlack='\e[0;90m' # Black
declare -grx Color_IRed='\e[0;91m' # Red
declare -grx Color_IGreen='\e[0;92m' # Green
declare -grx Color_IYellow='\e[0;93m' # Yellow
declare -grx Color_IBlue='\e[0;94m' # Blue
declare -grx Color_IPurple='\e[0;95m' # Purple
declare -grx Color_ICyan='\e[0;96m' # Cyan
declare -grx Color_IWhite='\e[0;97m' # White
}
# Bold High Intensity
colors_bold_high_intensity () {
declare -grx Color_BIBlack='\e[1;90m' # Black
declare -grx Color_BIRed='\e[1;91m' # Red
declare -grx Color_BIGreen='\e[1;92m' # Green
declare -grx Color_BIYellow='\e[1;93m' # Yellow
declare -grx Color_BIBlue='\e[1;94m' # Blue
declare -grx Color_BIPurple='\e[1;95m' # Purple
declare -grx Color_BICyan='\e[1;96m' # Cyan
declare -grx Color_BIWhite='\e[1;97m' # White
}
# High Intensity backgrounds
colors_high_intensity_background () {
declare -grx Color_On_IBlack='\e[0;100m' # Black
declare -grx Color_On_IRed='\e[0;101m' # Red
declare -grx Color_On_IGreen='\e[0;102m' # Green
declare -grx Color_On_IYellow='\e[0;103m' # Yellow
declare -grx Color_On_IBlue='\e[0;104m' # Blue
declare -grx Color_On_IPurple='\e[0;105m' # Purple
declare -grx Color_On_ICyan='\e[0;106m' # Cyan
declare -grx Color_On_IWhite='\e[0;107m' # White
}
# Main function
colors_main () {
if [[ -n ${_BASH_COLORS_:-""} ]] ; then
return
fi
export _BASH_COLORS_="bash_colors loaded"
colors_regular
colors_bold
colors_underline
colors_background
colors_high_intensity
colors_bold_high_intensity
colors_high_intensity_background
}
colors_main "${@}"
# shellcheck disable=SC2148
# remote-host-completion script
# -----------------------------
# Load common functions
load_servers_accounts_common () {
SILENT="true"
# shellcheck source=/home/alex/Documents/scripts/common.sh
source common.sh --no-script
}
# Autocomplete a single host, like <COMMAND> <HOST>
complete_single_hosts () {
load_servers_accounts_common
COMPREPLY=()
if [[ ${COMP_CWORD} != 1 ]] ; then
return
fi
local current="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD - 1]}"
load_server_account_file_if_needed
local existing_hosts="${!REMOTE_SERVERS_ACCOUNTS[*]}"
COMPREPLY=($(compgen -W "${existing_hosts}" -- "${current}"))
}
# Autocomplete a single argument with both account and host, like <COMMAND> <ACCOUNT>@<HOST>
complete_single_account_and_hosts () {
load_servers_accounts_common
COMPREPLY=()
if [[ ${COMP_CWORD} != 1 ]] ; then
return
fi
local current="${COMP_WORDS[COMP_CWORD]}"
load_server_account_file_if_needed
local account_server_combinations
for server in ${!REMOTE_SERVERS_ACCOUNTS[*]} ; do
for account in ${REMOTE_SERVERS_ACCOUNTS[*]} ; do
account_server_combinations+="${account}@${server} "
done
done
COMPREPLY=($(compgen -W "${account_server_combinations}" -- "${current}"))
}
# Autocomplete for the remote-session.sh script
complete_remote_session () {
load_servers_accounts_common
COMPREPLY=()
local current="${COMP_WORDS[COMP_CWORD]}"
local prev="${COMP_WORDS[COMP_CWORD - 1]}"
load_server_account_file_if_needed
local completions
# complete args -a or -s, ignore others
case "${prev}" in
"-s") completions="${!REMOTE_SERVERS_ACCOUNTS[*]}"
;;
"-a") completions="${REMOTE_SERVERS_ACCOUNTS[*]}"
;;
*) return
;;
esac
COMPREPLY=($(compgen -W "${completions}" -- "${current}"))
}
# Set-up completion
complete_remote_host_main () {
# Commands that work with a single argument (the host)
complete -F complete_single_hosts s
complete -F complete_single_hosts o
complete -F complete_single_hosts i
complete -F complete_single_hosts c
# Command that work with a single argument (account@host)
complete -F complete_single_account_and_hosts sshs
# Specific for script remote-session
complete -F complete_remote_session remote-session.sh
return 0
}
# Call main function
complete_remote_host_main "${@}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment