Permalink
Switch branches/tags
Nothing to show
Find file Copy path
1811d15 Apr 26, 2018
1 contributor

Users who have contributed to this file

302 lines (278 sloc) 10.1 KB
#!/bin/bash
#######################################################
# Local AND Remote aliases
#
alias fuck='cmd="$(fc -ln -1)" && echo "$cmd" && sudo $cmd'
# This trick enables aliases for sudo (the space after sudo)
alias sudo='sudo '
alias ll='ls -l --color=auto'
alias la='ls -la --color=auto'
alias ls='ls --color=auto'
# For btrfs
alias cp='cp --reflink=auto'
alias btrfs-grepdel='__grepdel() { sudo btrfs subvol list "$1" | awk -v p="$2" '\''$0 ~ p{ print "/"$9 }'\'' | xargs -t sudo btrfs sub del; }; __grepdel'
alias df='__df_findmnt() { [[ "$1" == "-h" || -z "$1" ]] && findmnt -D || df "$@"; }; __df_findmnt'
alias btrbk='btrbk -c /etc/btrbk/$(hostname -s).conf'
alias dracut-latest='dracut -f --kver="$(ls -1 /usr/lib/modules | sort -V | tail -n1)"'
alias dmesg='dmesg -xTk'
iptables-pretty() {
sudo iptables -nvL "$@" \
| awk '/^Chain/{ gsub(" +","$"); printf "#%s\n", $0; next}; gsub("[ ]+"," ")' \
| column -tE1 \
| sed '/^ *$/d;s|\$| |g; s|#|\n|g; /^Chain/!s|^| |'
}
alias pkcon-offline='pkcon refresh force -c -1 -y && pkcon update --only-download -y ; pkcon offline-trigger -y ; pkcon offline-get-prepared -y'
multiborg() {
for i in /mnt/external1/backups/*; do
sudo BORG_PASSCOMMAND='cat /root/.borg_password' borg "$@" "$i"
echo
done
}
snapper-space() {
snapper_mount() {
local type="$1"; shift
snapper -c "$1" list | awk '$3 ~ /[0-9]/ && $3 != 0 { print $3 }' | xargs -n1 snapper -c "$1" "$type"
}
snapper_mount mount "$1"
sudo lvs | grep "$1" | sort -Vk1
snapper_mount umount "$1"
}
# BEGIN DOCKER - https://gist.github.com/xenithorb/c0fdae80878a010759b2a3d1d76cf608
# Remove all docker containers running and exited
alias docker-rma='__drma() { docker ps -aq "$@" | xargs -r docker rm -f; }; __drma'
# Remove all docker images
alias docker-rmia='__drmia() { docker images -q "$@" | xargs -r docker rmi -f; }; __drmia'
# Remove all custom docker networks
alias docker-rmnet='__drmnet() { docker network ls -q -f type=custom "$@" | xargs -r docker network rm; }; __drmnet'
# Remove all unused volumes
alias docker-rmvol='__drmvol() { docker volume ls -q "$@" | xargs -r docker volume rm; }; __drmvol'
# Remove all docker containers and all docker images
alias docker-rmall='docker-rma && docker-rmia'
# Remove all docker containers, images, custom networks, and volumes
alias docker-nuke='docker-rmall; docker-rmnet; docker-rmvol'
# Remove only exited containers, unused images, unused networks, and unused volumes
alias docker-clean='docker-rma -f status=exited; docker-rmia -f dangling=true; docker-rmnet; docker-rmvol -f dangling=true'
# END DOCKER
alias mockbuild='\
__mock() {
local SPEC="$1" \
&& shift \
&& rpmlint "$SPEC" \
&& spectool -g "$SPEC" \
&& local SRPM=$( mock "$@" -v --resultdir . --buildsrpm --spec "$SPEC" --sources . 2>&1 | awk "/ Wrote: /{ print gensub(\".*/([^/]+)$\",\"\\\1\",\"g\",\$3) }" ) \
&& mock "$@" --resultdir . "${SRPM:?ERROR: Missing SRPM}"; \
}; __mock'
alias spec-show='find . -name *.spec | xargs awk '\''BEGIN{ format="%s %s %s %s\n"; printf format,"NAME","VERSION","RELEASE","SPECFILE" }; /Name: /{ n=$2; next }; /Version: /{ v=$2; next }; /Release: /{ r=$2; sub("%.*","",r); printf format,n,v,r,FILENAME }'\'' | column -t | ( read -r; echo "$REPLY"; sort)'
alias mockbuild_noclean='_mock_nc() { mockbuild "$@" --no-cleanup-after --no-cleanup; }; _mock_nc'
alias mkgrub='sudo sh -c "grub2-mkconfig | tee /etc/grub*.cfg >/dev/null"'
alias userinstalled='readarray -t nevra < <(sudo dnf history userinstalled); rpm -q --qf="%{name}\n" "${nevra[@]}"'
alias vagrant-killall="vagrant global-status | sed '/------/,/^ \$/!d;/^ \$/d;2d' | awk '{print \$1}' | xargs vagrant destroy -f"
alias tmux='tmux -f ${__TMUXRC}' # __TMUXRC is in .common
# Please god help me remember dnf/yum
if hash dnf &>/dev/null; then
alias dnf-repowhere='dnf repoquery --qf="%{name}-%{version}-%{release}.%{arch}\t%{reponame}"'
alias yum='dnf'
elif hash yum &>/dev/null; then
alias yum-repowhere='repoquery --qf="%{name}-%{version}-%{release}.%{arch}\t%{repoid}"'
alias dnf='yum'
elif hash apt-get &>/dev/null; then
echo "Debian, really? Idiot!"
fi
if command -v pygmentize &>/dev/null; then
alias pcat='pygmentize -g'
pless() { pygmentize -g < "${1:-/dev/stdin}" | less -R; };
fi
# Ok got me, not aliases but they act like ones
# Neat little script to upload files to hastebin.com
if hash curl &>/dev/null; then
haste() {
local S="https" H="hastebin.com" P="" L="$1"
local SHP="${S}://${H}${P}/"
curl -X POST -s --data-binary @- "${SHP}documents" \
| awk -F '"' 'b{ b="."b }; {print a$4b}' a="${SHP}" b="${L}"
}
fi
# BEGIN DOCKER-DIND - https://gist.github.com/xenithorb/5a76b018967ef33d6123c06781791877
if command -v docker &>/dev/null; then
dind () { docker-dind "$@"; }
dind-deactivate() { unset DOCKER_HOST; }
dind-activate () { unset DOCKER_HOST; dind-info; export DOCKER_HOST="$DOCKER_DIND_HOST" DOCKER_DIND_PORTS; }
dind-info () {
local info host_info dind_info tmpfile dind_good
info="{{.Name}}, {{.ServerVersion}}, {{.OperatingSystem}}"
host_info=$(DOCKER_HOST='' docker info -f "$info")
tmpfile="/tmp/docker-dind-out.$$"
docker-dind info -f "$info" > "$tmpfile"; dind_good="$?"
dind_info=$(<"$tmpfile"); rm -f "$tmpfile"
if [[ "$host_info" == "$dind_info" ]] || (( dind_good != 0 )); then
echo "DIND NOT ACTIVE: ${dind_info}"
else
echo -ne "DIND ACTIVATED:\n\tHOST: ${host_info}\n\tDIND: ${dind_info}" \
"\n\n\tForwarded Ports: ${DOCKER_DIND_PORTS}\n"
fi
}
docker-dind () {
local port host id range_s range_e count name
name=docker_dind; host=localhost; port=4444; range_s=10001; range_e=10101
if (( $(docker ps -q -f name="${name}" | wc -l) <= 0 )); then
docker run --privileged \
-e PORT="$port" -p "${port}":2375 \
--net host \
-v "${name}:/var/lib/docker" \
--name "${name}" \
-d docker:dind \
dockerd --host unix:///var/run/docker.sock \
--host tcp://0.0.0.0:${port} \
>/dev/null
fi &&
until (( $(curl -sio /dev/null -w "%{http_code}" http://${host}:${port}/_ping) == 200 )); do
sleep .1; (( count > 50 )) \
&& { echo "Cannot connect to DinD daemon"; return 1; } \
|| ((++count))
done
if [[ $(DOCKER_HOST='' docker inspect ${name} --format="{{ .HostConfig.NetworkMode }}") == "host" ]]; then
DOCKER_DIND_PORTS="NONE: In host network mode"
else
DOCKER_DIND_PORTS="${range_s}${range_e:+-${range_e}}"
fi
export DOCKER_DIND_HOST="${host}:${port}" DOCKER_DIND_PORTS
DOCKER_HOST="$DOCKER_DIND_HOST" docker "$@"
}
fi
# END DOCKER-DIND
replace_in_file_recursive() {
trap 'unset files' RETURN
local a="$1" b="$2" nl=$'\n'
readarray -t files < <(grep -Rli "$a")
(( "${#files[@]}" == 0 )) && { echo "No files match!"; return 1; }
cat <<-EOF
Files:
$(
for ((i=0;i<${#files[@]};i++)); do
local grep_line="$(grep --color="always" -h "$a" "${files[i]}")"
lines+=( "${files[i]}%%%${grep_line}" )
done
printf "\n\t%s" "${lines[@]}" |column -t -s'%%%'
)$nl
Replace all occurances of "$a" with "$b"?
EOF
select prompt in "Yes" "No"; do
case $prompt in
Yes) sed -i "s|${a}|${b}|g" "${files[@]}"; return ;;
No) return ;;
esac
done
}
if hash dnf &>/dev/null; then
# Remove repo and packages together
dnf-nukerepo() {
get_num_pkgs() {
sudo dnf repo-pkgs "$1" list installed \
| awk 'NR<3 && /^(Last metadata|Installed)/{--NR}; END { print NR }'
}
delete_repo() {
printf "%s %s\n" "Deleting repo:" "$1"
sudo dnf repolist -v --repoid "$1" \
| awk '/Repo-filename/{ print $2 }' | xargs -r sudo rm
}
local repo="$1"
if [[ "$(get_num_pkgs "$repo")" -gt 0 ]]; then
sudo dnf repo-pkgs "$repo" remove
if [[ "$(get_num_pkgs "$repo")" -eq 0 ]]; then
delete_repo "$repo"
fi
else
delete_repo "$repo"
fi
}
# Print what group a package is in
dnf-groupfind() {
sudo dnf group info '*' \
| awk -v package="$1" \
-v red="$(tput setaf 196)" \
-v rst="$(tput sgr0)" \
'
BEGIN {
FS=": "
group_reg="^Group: "
opt_reg="^ Optional Packages:"
}
$0 ~ group_reg { group=$2 }
$0 ~ opt_reg { opt=group }
$0 ~ "^[ ]*"package {
name=$1
found=1
gsub(" ","",name)
if ( opt == group ) {
print name,"-",group,red"- Optional"rst" ( add \"with-optional\" to dnf group install command )"
} else {
print name,"-",group
}
}
END {
if ( ! found ) { print red"Not found."rst }
}
'
}
fi
# end dnf if
# Find listening ports of a service cgroup
# https://www.redpill-linpro.com/sysadvent/2016/12/22/systemd-at-3am.html
lsof_listen() {
local pids=$( ps -e -o pid,cgroup | awk '$2 ~ /'"$1"'/ { print "-p", $1 }' )
sudo lsof -n -i -a -P ${pids:?ERROR: No PIDs found.}
}
# Useful to output the cert information of a domain
openssl_sclient() {
openssl s_client -connect "$1" 2>&1 </dev/null \
| sed '/^-----/,/^-----/!d' \
| openssl x509 -noout -text \
| sed -r '/:[[:alnum:]]{2}:$/d'
}
# BEGIN JSON2YAML - https://gist.github.com/xenithorb/e90713534624c93a834a92c2a0c6ee28
yaml2json() {
python < "${1:-/dev/stdin}" <(
cat <<-EOF
import sys, yaml, json
json.dump(yaml.load(sys.stdin), sys.stdout, indent=4)
EOF
)
}
json2yaml() {
python < "${1:-/dev/stdin}" <(
cat <<-EOF
import sys, yaml, json
yaml.safe_dump( json.load(sys.stdin),
sys.stdout,
explicit_start=True,
default_flow_style=False
)
EOF
)
}
# END JSON2YAML
ansible-ssh_completion() {
local host_list=($( ansible-inventory --list | python3 -c 'import sys, json; a=json.load(sys.stdin); print("\n".join(a["_meta"]["hostvars"].keys()))' ))
if (( ${#COMP_WORDS[@]} < 3 )); then
local suggestions=($( compgen -W "${host_list[*]}" -- "${COMP_WORDS[1]}" ))
fi
if (( ${#suggestions[@]} > 1 )); then
for (( i=0; i<${#suggestions[@]}; i++ )); do
suggestions[i]=$( printf '%*s' "-$COLUMNS" "${suggestions[i]}" )
done
fi
COMPREPLY=( "${suggestions[@]}" )
}
ansible-ssh() {
local host=$1
shift
eval $(ansible-inventory --host "$host" \
| python -c "$( cat <<-EOF
import sys, subprocess, json
a=json.load(sys.stdin)
print( " ".join(["ssh", "-tt", "-P" + str(a["ansible_port"]), a["ansible_user"] + "@" + a["ansible_host"]]) )
EOF
)"
) "$@"
}
complete -F ansible-ssh_completion ansible-ssh