1
0
mirror of https://git.decapod.one/brethil/dotfiles synced 2024-11-24 04:21:31 +01:00

New repo initial commit

This commit is contained in:
bretello 2017-06-12 16:22:05 +02:00
commit d8d2c7a512
9 changed files with 946 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@ -0,0 +1 @@
.DS_store

66
README.md Normal file
View File

@ -0,0 +1,66 @@
# brethil's dotfiles #
## Description ##
1. brethil_dotfile.sh: main file sourced by ~/.bash_profile
2. aliases.sh: contains alias definitions (sources ~/.bash_aliases)
3. functions.sh: contains function definitions (sources ~/.bash_functions)
4. colors.sh: contains color definitions
5. install.sh: run to install brethil's dotfiles
## Installation ##
Copy the dotfiles folder to the location where you want to keep it and then run install:
$ cd dotfiles && bash install.sh
Installs oh-my-zsh and sources aliases.sh, functions.sh and colors.sh, as well as installing
a a few utilities (see `install.sh`)
### Installed programs ###
0. oh-my-zsh (zsh config)
1. byobu (wrapper/config for tmux, a screen multiplexer)
2. grc (generic colourizer, colours output of any command)
3. bmon (bandwidth monitor, shows graphs for bandwith usage)
3. rmate remote for Textmate (can be called with `mate`/`rmate`)
### Available Commands ###
1. Quickly edit/reload profile (`esource`/`resource`)
2. `ramdisk` (only on OSX) create a RAM disk. Default size: 1GB
` ramdisk 4`
creates a 4GB RAM disk
3. `color` to print colored text (see 3. in the Misc section):
color red "This will be printed in red"
4. `mecp` to copy files back to the machine from wich you are ssh-ing.
For this to work an ssh tunnel with Remoteforward is needed:
ssh -R 22:localhost:2222 YOURHOSTNAMEHERE
or specify this in ~/.ssh/config:
Host YOURHOSTNAMEHERE
Remoteforward 2222 localhost:22
You might have to manually edit the username in the mecp definition in functions.sh if this is
different between the two machines. mecp copies by default on the local machine on ~/Desktop/
5. Many more. Type "list_functions" to list defined functions and a small description
### Files/Folders ###
1. `~/bin`, `~/python`, `~/projects` folders
2. ssh config (`~/.ssh/config`):
* Create ssh keys if not defined already
* Keep connections alive by increasing timeout time
* Include multiplexer to allow quick multiple connections to the same host
* (Optional: Compression, this should allow more responsive shells with slow connections,
but will slow things down when copying large files. My suggestion is to have compression enabled
on a by-host basis in `~/.ssh/config`)
3. brethil.zsh-theme, theme for oh-my-zsh, installed in ~/.oh-my-zsh/themes/
4. ~/.dotfiles_functions, ~/.dotfiles_aliases are sourced by this dotfiles, allowing for custom functions/aliases
5. useful_commands contains a list of useful commands (the first rule of the tautology club...)
### Misc ###
1. Colored output for `ls`/`grep`/`man`
2. Easy names for ANSI color escapes (Black, Red, Green, Yellow, Blue, Cyan, Purple, White, CLEAR),
for example:
`echo -e "${Green}This text will be green${CLEAR}"`
will result in green text. Use `$CLEAR` to clear previous escale sequences add B before the variable
name to use **bold** and U to underline (examples: $BRed, $UBlack for bold red and underlined black)

92
aliases.sh Executable file
View File

@ -0,0 +1,92 @@
###########################
#### ALIAS #
###########################
####
#### Easier life (MAC SPECIFIC)
####
if [[ "$(uname)" == "Darwin" ]]; then
alias o="open"
alias ls="ls -G"
## Colorize system.log contents (with grc), and inspect with less.
alias console="grc cat /var/log/system.log | sort -r | less -R"
## Quicklook shortcut
alias quicklook='qlmanage -px 2>/dev/null'
alias ql='qlmanage -px'
## Airport command line interface
alias airport='/System/Library/PrivateFrameworks/Apple80211.framework/Resources/airport'
## Set an English locale to awk (default is italian, with commas as decimal separators)
alias awk='LC_ALL=en_DK awk'
## Flush dns cache
#alias dnsflushcache='sudo discoveryutil mdnsflushcache' # used to work until 10.6
alias dnsflushcache='sudo killall -HUP mDNSResponder' # Works up until 10.9 and after 10.10.4
## Add opened files to Textmate's recent menu item
alias mate='mate --recent'
fi
####
#### Easier life (everything)
#### Audible bell
alias bell='echo -en "\007"'
alias grep="grep --color=auto"
##############
## ls aliases
############
# ls -al, only show files that start with a dot
alias lsdot="ls -al | awk '\$9 ~ /^\./ {print \$0}'"
alias lt='ls -lrt | tail -10'
alias ll='ls -lhL' #long ls output
alias ka="killall"
## Load pylab by default when running ipython
alias ipy="ipython --pylab"
## Go up one directory or several (with integer argument)
alias upcd='. upcd.sh'
## Show the last 10 modified files
alias lsrt="ls -lrt | tail -10"
#####################
#### New features
#####################
## List open connections (+c flag is to show command name with 15 characters (what the system provides))
alias listconnections="lsof +c 15 -r -i TCP -i UDP"
## Stress (run stress &>/dev/null &)
alias stress='yes >> /dev/null'
# use textmate to diff two files
alias mdiff="mate -t source.diff"
###########################
#### SSH Tunnels #
###########################
# define ssh without controlmaster
alias ssh1="ssh -o ControlMaster=no"
# Colorizing aliases (using grc)
alias ps="grc ps"
alias ping="grc ping"
alias traceroute="grc traceroute"
alias mtr="grc mtr"
if [[ -f ~/.dotfiles_aliases ]];
then
source ~/.dotfiles_aliases
fi

8
brethil.zsh-theme Normal file
View File

@ -0,0 +1,8 @@
ret_status="%(?:%{$fg_bold[green]%}➜%{$reset_color%}:%{$fg[red]%}➜%{$reset_color%})"
user="%(#:root@:)"
PROMPT='[%*][%{$fg[red]%}${user}%M%{$reset_color%}][:%{$fg[green]%}%c%{$reset_color%}]$(git_prompt_info) ${ret_status} '
ZSH_THEME_GIT_PROMPT_PREFIX=" %{$fg[yellow]%}git:("
ZSH_THEME_GIT_PROMPT_SUFFIX="%{$fg[yellow]%})%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_DIRTY="%{$fg[white]%} %{$fg[red]%}✗%{$reset_color%}"
ZSH_THEME_GIT_PROMPT_CLEAN="%{$fg[white]%} %{$fg[green]%}√%{$reset_color%}"

57
brethil_dotfile.sh Executable file
View File

@ -0,0 +1,57 @@
if [[ "$SHELL" == *"bash" ]]; then
alias resource="source $HOME/.bash_profile"
alias esource="mate -t source.shell $HOME/.bash_profile"
elif [[ "$SHELL" == *"/zsh" ]]; then
alias resource="source $HOME/.zshrc"
## zsh plugins, these can be installed easily with zplug
#if [[ "$(uname)" == "Darwin" ]]; then
# plugins=(git common-aliases osx macports textmate anybar)
#else
# plugins=(git common-aliases)
#fi
alias esource="mate -t source.shell $HOME/.zshrc"
fi
alias dotedit="mate -t source.shell $DOTFILES/brethil_dotfile.sh"
alias funedit="mate -t source.shell $DOTFILES/functions.sh"
alias aledit="mate -t source.shell $DOTFILES/aliases.sh"
# Extras
functions_file=$DOTFILES/functions.sh # Function definitions
aliases_file=$DOTFILES/aliases.sh # Aliases definitions
colors_file=$DOTFILES/colors.sh # Colors definitions
# Source extras
if [ -f $functions_file ]; then source $functions_file; fi
if [ -f $aliases_file ]; then source $aliases_file; fi
if [ -f $colors_file ]; then source $colors_file; fi
########################
## Make prompt prettier
######################
if [[ -e $BASH ]]; then
export PROMPT_COMMAND='echo -ne "\033]0;${PWD/#$HOME/~}\007"'
## This prompt only contains date, username and path, prints a red 'x' when a commands fails
#export PS1='[\t][:\w]$(if [[ $? != 0 ]]; then printf "[\[\e[31m\]✗\[\e[0m\]] "; else printf " "; fi)'
promptred="\[\033[1;31m\]"
promptgreen="\[\033[1;32m\]"
promptclear="\[\033[m\]"
export PS1="[\t][$promptred\h$promptclear][:$promtgreen\w$promptclear] "
### Other prompt choices:
## This prompt includes includes host name
# export PS1='[\t][\h][\u:\w] '
## This prompt only includes username, date and path
#export PS1='[\t][\u:\w] '
fi
export EDITOR="mate -w"
### SETUP PATHS ####
export PATH=$PATH:$HOME/bin/
export PYTHONPATH=$PYTHONPATH:$HOME/python/:$HOME/bin
## One can also use most pager instead of less to visualize man pages
#export PAGER="most"

88
colors.sh Executable file
View File

@ -0,0 +1,88 @@
# ANSI COLOR ESCAPES
# CLEAR
CLEAR='\e[0m' # CLEAR
# Regular Colors
Black='\e[0;30m' # Black
Red='\e[0;31m' # Red
Green='\e[0;32m' # Green
Yellow='\e[0;33m' # Yellow
Blue='\e[0;34m' # Blue
Purple='\e[0;35m' # Purple
Cyan='\e[0;36m' # Cyan
White='\e[0;37m' # White
# Bold
BBlack='\e[1;30m' # Black
BRed='\e[1;31m' # Red
BGreen='\e[1;32m' # Green
BYellow='\e[1;33m' # Yellow
BBlue='\e[1;34m' # Blue
BPurple='\e[1;35m' # Purple
BCyan='\e[1;36m' # Cyan
BWhite='\e[1;37m' # White
# Underline
UBlack='\e[4;30m' # Black
URed='\e[4;31m' # Red
UGreen='\e[4;32m' # Green
UYellow='\e[4;33m' # Yellow
UBlue='\e[4;34m' # Blue
UPurple='\e[4;35m' # Purple
UCyan='\e[4;36m' # Cyan
UWhite='\e[4;37m' # White
# Background
On_Black='\e[40m' # Black
On_Red='\e[41m' # Red
On_Green='\e[42m' # Green
On_Yellow='\e[43m' # Yellow
On_Blue='\e[44m' # Blue
On_Purple='\e[45m' # Purple
On_Cyan='\e[46m' # Cyan
On_White='\e[47m' # White
# High Intensity
IBlack='\e[0;90m' # Black
IRed='\e[0;91m' # Red
IGreen='\e[0;92m' # Green
IYellow='\e[0;93m' # Yellow
IBlue='\e[0;94m' # Blue
IPurple='\e[0;95m' # Purple
ICyan='\e[0;96m' # Cyan
IWhite='\e[0;97m' # White
# Bold High Intensity
BIBlack='\e[1;90m' # Black
BIRed='\e[1;91m' # Red
BIGreen='\e[1;92m' # Green
BIYellow='\e[1;93m' # Yellow
BIBlue='\e[1;94m' # Blue
BIPurple='\e[1;95m' # Purple
BICyan='\e[1;96m' # Cyan
BIWhite='\e[1;97m' # White
# High Intensity backgrounds
On_IBlack='\e[0;100m' # Black
On_IRed='\e[0;101m' # Red
On_IGreen='\e[0;102m' # Green
On_IYellow='\e[0;103m' # Yellow
On_IBlue='\e[0;104m' # Blue
On_IPurple='\e[0;105m' # Purple
On_ICyan='\e[0;106m' # Cyan
On_IWhite='\e[0;107m' # White
# ANSI COLOR ESCAPES 2
## Clear all previous sequences
# Bold text
BOLD="\e[1m"
# Colors: Black, Blue, Green, Cyan, Red, Purple, Brown, LightGray
BLACK="\e[30m"; BLUE="\e[34m"; GREEN="\e[32m"; CYAN="\e[36m";
RED="\e\[31m"; PURPLE="\e[35m"; BROWN="\e[33m"; LIGHTGRAY="\e[37m";
DARKGRAY="\e[30m"; LIGHTBLUE="\e[34m"; LIGHTGREEN="\e[32m";
LIGHTCYAN="\e[36m"; LIGHTRED="\e[31m"; LIGHTPURPLE="\e[35m";
YELLOW="\e[33m"; WHITE="\e[37m"
BACKGROUND_BLACK="\e[40"; BACKGROUND_RED="\e[41";
BACKGROUND_GREEN="\e[42"; BACKGROUND_YELLOW="\e[43m"

191
functions.sh Executable file
View File

@ -0,0 +1,191 @@
###########################
#### Function Definitions #
###########################
## Simple calculator. Usage: calc 1+1, calc 5/7, calc "sqrt(2)"
function calc {
awk "BEGIN { print "$*" }"
}
## Open Man in separate (good looking) window
function nman
{
if [ $# -eq 1 ] ;
then open x-man-page://$1 ;
elif [ $# -eq 2 ] ;
then open x-man-page://$1/$2 ;
fi
}
## Open a pdf version of the man in Preview
function man2pdf
{
man -t "$1" | open -f -a Preview
}
## Make new directory and cd to that directory
function mcd
{
mkdir -p $1
cd $1
}
## Print full path of item in current directory
function ppath
{
echo $PWD/"$1"
}
## Color string with given color. Usage: color colorname "string", available colors in colors.sh
function color
{
color=$1
shift 1
printf "$color$@$CLEAR"
}
## These functions return a colored version of the input string
function red
{
echo -e "$RED$@$CLEAR"
}
function green {
echo -e "$GREEN$@$CLEAR"
}
function blue {
echo -e "$BLUE$1$CLEAR"
}
## Flashes the screen until user presses a key
function flasher
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n1 -t1 && break; done;
}
## Beep until user presses a key
function beeper
{
while true; do printf "\e[?5h\007"; sleep 0.25; printf "\e[?5l"; read -s -n1 -t1 && break; done;
}
## Search youtube for string ($1) and play video
function pyt
{
echo 'https://www.youtube.com/results?search_query='"$(sed 's/ /%20/g' <<< $(tr '\' '+' <<< "$@"))"; id=$(curl -s 'https://www.youtube.com/results?search_query='"$(sed 's/ /%20/g' <<< $(tr '\' '+' <<< "$@"))" | grep -om3 '"[[:alnum:]]\{11\}"' | awk NR==3 | tr -d \"); url='https://www.youtube.com/watch?v='"$id"; echo -e "URL:\t$url"; youtube-dl -q $url -o - | mplayer -vo corevideo -really-quiet /dev/fd/3 3<&0 </dev/tty;
}
## Same as above, only play music
function pmusic
{
echo 'https://www.youtube.com/results?search_query=HD%20'"$(sed 's/ /%20/g' <<< $(tr '\' '+' <<< "$@"))"; id=$(curl -s 'https://www.youtube.com/results?search_query='HD%20"$(sed 's/ /%20/g' <<< $(tr '\' '+' <<< "$@"))" | grep -om3 '"[[:alnum:]]\{11\}"' | awk NR==3 | tr -d \"); url='https://www.youtube.com/watch?v='"$id"; echo -e "URL:\t$url"; youtube-dl -q $url -o - | mplayer -vo corevideo -really-quiet /dev/fd/3 3<&0 </dev/tty;
}
## Simple http server for current directory (or path)
function httpserver
{
cwd="$pwd"
if [[ -e $1 ]];
then
dir="$1"
else
dir="$pwd"
fi
cd "$dir"
sleep 0.1 && open "http://localhost:8000" &>/dev/null &
python -m SimpleHTTPServer
}
## Upload something using the transfer.sh service
function transfer
{
basefile=$(basename "$1" | sed -e 's/[^a-zA-Z0-9._-]/-/g')
out=$(curl --progress-bar --upload-file "$1" "https://transfer.sh/$basefile")
echo -e "Done, file at:\t$out"
echo "$out" | pbcopy
}
## List defined functions in $DOTFILES/functions.sh
function list_functions
{
cat $DOTFILES/functions.sh | grep --color=no -A 1 '^## ' | sed -E 's/function (.*)/\1()/g'
}
# If connecting through ssh and reverse forwarding port 2222 (ssh -R 2222:localhost:22 ), this function allows to copy the files back to the machine one is connecting from by typing 'mecp filename' (configure the username for "localhost" in ~/.ssh/config or add an username)
function mecp
{
rsync -r -P -e "ssh -p 2222" -R "$@" localhost:~/Desktop/
}
# generate a password using pwgen, generate_password 20 generates a 20 characters long password
function generate_password
{
pwgen -1sycn $1
}
# Generate a password from dev urandom using only printable characters
function genpwd {
if [[ -e $1 ]]; then
strlen=$1
else
strlen=32
fi
cat /dev/urandom | env LC_CTYPE=C tr -dc '[:graph:]' | fold -w $strlen | head -n 1
}
if [[ "$(uname)" == "Darwin" ]]; then
# Copy output of previous command to termbin.com (command line pastebin) and put in in clipboard
function termbin {
nc termbin.com 9999 | pbcopy && echo -n "$(pbpaste) --> in clipboard"
}
else
function termbin {
nc termbin 9999
}
fi
###########################
## MAC SPECIFIC #
###########################
if [[ "$(uname)" == "Darwin" ]];
then
## Create a RAM disk. Default size 1GB. If supplied, first argument defines the RAM disk size in GB
function ramdisk {
if [[ -e $1 ]];
then
sizeingb=$1
else
sizeingb=1
fi
# Numsectors is size in bytes / 512 (sector size in bytes)
name='RAM_disk'
sizeinbytes=$(($sizeingb*1000**3))
NUMSECTORS=$(($sizeinbytes/512))
mydev=$(hdiutil attach -nomount ram://$NUMSECTORS )
# strip whitespace (hdiutil outputs a lot of spaces/tabs along with the device name)
mydev=$(echo "$mydev"| xargs echo)
newfs_hfs $mydev
mkdir -p "/tmp/$name"
mount -t hfs $mydev "/tmp/$name"
echo "RAM Disk mounted: /tmp/$name"
echo "To eject (destroy) RAM disk, use:"
echo " $ diskutil eject $mydev"
}
# Anybar support https://github.com/tonsky/AnyBar
function anybar { echo -n $1 | nc -4u -w0 localhost ${2:-1738}; }
fi
if [[ -f ~/.dotfiles_functions ]];
then
source ~/.dotfiles_functions
fi

189
install.sh Executable file
View File

@ -0,0 +1,189 @@
#!/bin/bash
## brethil's dotfiles installation file
## 20 June 2016
# Get the location for the dotfiles
DOTFILES=$PWD
echo -e "\n\n# Beginning of brethil's dotfiles:" >> ~/.zshrc
echo "DOTFILES=$DOTFILES" >> ~/.zshrc
echo "source \$DOTFILES/brethil_dotfile.sh" >> ~/.zshrc
function install_rmate {
## Ruby version:
#curl -Lo ~/bin/rmate https://raw.github.com/textmate/rmate/master/bin/rmate
## Python version:
echo "Installing rmate (python)..."
if [[ $(whoami) == "root" ]]; then
destpath="/usr/bin"
else
destpath="$HOME/bin"
fi
curl -sL https://raw.githubusercontent.com/sclukey/rmate-python/master/bin/rmate >> $destpath/rmate
chmod a+x $destpath/rmate
ln -s $destpath/rmate $destpath/mate || "Could not create symbolic link to $destpath/mate (already exists?)"
echo "Installed rmate (and mate symlink) in $destpath"
}
function install_vimrc {
git clone https://github.com/amix/vimrc.git $HOME/.vim_runtime
sh $HOME/.vim_runtime/install_awesome_vimrc.sh
}
function install_zsh_plugins {
# Install fast-syntax-highlighting zsh-autosuggestions
ZSH_PLUGINS="$HOME/.oh-my-zsh/custom/plugins"
git clone https://github.com/zdharma/fast-syntax-highlighting.git ${ZSH_PLUGINS}/fast-syntax-highlighting
git clone git://github.com/zsh-users/zsh-autosuggestions ${ZSH_PLUGINS}/zsh-autosuggestions
}
# Add an ssh config file with:
# - Connection multiplexer for faster multiple connections
# - Keep connections alive (avoid timeout disconnections)
function create_ssh_config {
echo "# Configuring ssh..."
ssh_config="$HOME/.ssh/config"
if [ ! -d $HOME/.ssh/id_rsa ]; then
ssh-keygen -t rsa -b 4096
chmod 0700 "$HOME/.ssh"
fi
if [[ -f $ssh_config ]]; then
while [ "$modifyssh" != "y" ] && [ "$modifyssh" != "n" ]
do
echo "Do you want to modify the existing ssh config? (New values will be appended) (y/n)"
read modifyssh
done
fi
if [[ "$modifyssh" != "n" ]]
then
echo "# brethil's dotfiles setup start" >> $ssh_config
echo 'TCPKeepAlive=yes' >> $ssh_config
echo 'ServerAliveCountMax=6' >> $ssh_config
## Compression will slow things down when copying large files, but improve
## speed if only using a shell, my reccommendation is to enable it on a by-host
## basis in ~/.ssh/config
#echo ' Compression=yes' >> $ssh_config
#echo 'ControlMaster auto' >> $ssh_config
#echo 'ControlPath /tmp/%r@%h:%p' >> $ssh_config
#echo 'ControlPersist yes' >> $ssh_config
echo 'Host *' >> $ssh_config
echo 'ServerAliveInterval 300' >> $ssh_config
echo '# end of brethil dotfiles setup #' >> $ssh_config
## Enable the following if you want to use the rmate textmate remote
#echo "Host *" >> $ssh_config
#echo "RemoteForward 52698 localhost:52698" >> $ssh_config
## Enable the following if you want to use a reverse ssh tunnel (mecp)
#echo "Host *" >> $ssh_config
#echo "Remoteforward 2222 localhost:22" >> $ssh_config
#
echo ".ssh folder configured, enabled ControlMaster for all connections."
echo "Compression disabled, enable by uncommenting 'Compression' in ~/.ssh/config"
echo "Remote forwarding port 52698->52698 (Textmate) and port 2222->22 (mecp) for all hosts."
else
echo "Did not modify $ssh_config."
fi
echo "# End of ssh config."
}
# Run after first copying to a remote machine
function brethil_dotfiles_setup {
bin="$HOME/bin/"
#python="$HOME/python"
projects="$HOME/projects"
git="$HOME/git"
mkdir -p "$bin"
mkdir -p "$projects"
mkdir -p "$git"
echo "Created dirs $bin, $projects, $git"
# Install packages
# zsh
# byobu: configuration/wrapper for tmux
# grc: generic colourizer, colors output of any command
# bmon: bandwidth monitor, monitors bandwith usage, shows graph
# mtr: mytraceroute, traceroute tool
# pv: pipe view, monitor the progress of data through a pipe
# byobu: tmux wrapper
packages="zsh git grc bmon mtr pv tmux byobu"
# Check if running as root, if not, quit.
if [[ ! $(id -g) == 0 ]]; then
echo "This has to be run as root to install new software from the repos. Quitting..."
exit 0
fi
if [[ $(which apt-get ) ]]; then
install_command="apt-get install"
elif [[ $(which pacman) ]]; then
install_command="pacman -Sy"
elif [[ $(which yum) ]]; then
install_command="yum"
elif [[ $(which port) ]]; then
install_command="port install"
elif [[ $(which brew) ]]; then
install_command="brew install"
else
echo "Could not install required packages"
error=true
fi
if [[ ! $error ]]; then
$install_command $packages
# Install oh-my-zsh
echo "Installing oh-my-zsh..."
sh -c "$(curl -sL zsh.dioporc.one)"
## Fix scrolling in byobu
sed -i 's/set -g terminal-overrides/#set -g terminal-overrides/' /usr/share/byobu/profiles/tmux
echo "bind m setw -g mode-mouse on" >> ~/.tmux.conf
echo "bind M setw -g mode-mouse off" >> ~/.tmux.conf
fi
# Install the rmate client for textmate
install_rmate
# Install vim awesomerc (git amix/vimrc)
install_vimrc
# Create ssh config
create_ssh_config
# Install new zsh plugins in $ZSH/custom/plugins/
install_zsh_plugins
# Comment enabled plugins in ~/.zshrc
sed -e '/plugins=\(\.*\)/ s/^#*/#/' -i $HOME/.zshrc
# Enable these plugins:
plugins="plugins=(git common-aliases fast-syntax-highlighting zsh-autosuggestions colored-man-pages)"
echo $plugins >> $HOME/.zshrc
# Copy brethil.zsh-theme
ln -s $DOTFILES/brethil.zsh-theme $HOME/.oh-my-zsh/themes/
# Set brethil theme
sed -i 's/ZSH_THEME=".*"/ZSH_THEME="brethil"/' $HOME/.zshrc
}
# Setup
brethil_dotfiles_setup
echo "Functions are defined in $DOTFILES/functions.sh (you can add extra functions in ~/.dotfiles_functions)"
echo "Aliases are defined in $DOTFILES/aliases.sh (you can add extra aliases in ~/.dotfiles_aliases)"
echo "Colors are defined in $DOTFILES/colors.sh"
echo "These 3 files are sourced by $DOTFILES/brethil_dotfile.sh, which is in turn sourced by ~/.zshrc"
echo "Type . ~/.zshrc to source the new dotfiles, or simply launch another shell."

254
useful_commands Normal file
View File

@ -0,0 +1,254 @@
# A list of terminal commands/hacks for Mac OS X/BSD
# For a more comprehensive list:
# https://github.com/mathiasbynens/dotfiles/blob/master/.osx
#
# For another list
# http://www.commandlinefu.com/commands/browse/sort-by-votes/
# To search commandlinefu using the API:
cmdfu(){ curl "http://www.commandlinefu.com/commands/matching/$@/$(echo -n $@ | openssl base64)/plaintext"; }
#
# For a list of Mac OS X keyboard shortcuts:
# http://support.apple.com/kb/HT1343?viewlocale=en_US&locale=en_US
#
# Lots of interesting stuff:
# http://cb.vu/unixtoolbox.xhtml#other
#####################
### Bash
#####################
# List all bash shortcuts
bind -P
## Bash expansions:
!$ # expands to the last argument to the previous command
!* # expands to all the arguments to the previous command
!! # expands to the entirety of the last command
# you can mix all kinds of stuff, which makes history expansion super powerful:
!-2$: # the last argument to the next-to-last command
!ls:*: # all the arguments to the last command that starts with ls
!!:gs/foo/bar: # the last command with all instances of foo replaced with bar
# Re-run last command substituing the string 'before' with 'after' in the command
^before^after^
# Report the size of 'name'
du -sh name
# Quickly rename a file
mv filename.{old,new}
# Print only certain columns of a file:
cut -f column[,column1,...] filename
# Suppress command output (should be equivalent to 'noisycommand >> /dev/null' )
noisy_command >&-
# Run 'command' and convert output to png
command | convert label:@- ip.png
# Remove every file which has not extension foo, bar or baz
rm !(*.foo|*.bar|*.baz)
# Get info about filesystem hierarchy
man hier
# Define a calculator, exmaple of call '? 1+1' yields 2
? () { echo "$*" | bc -l; }
# Copy your public key to user@machine for ssh-key-based login
cat ~/.ssh/id_rsa.pub | ssh user@machine "mkdir -p ~/.ssh; chmod 0700 .ssh; cat >> ~/.ssh/authorized_keys"
# Intercept stdout,err of $PID. This might require root or special configurations
strace -ff -e trace=write -e write=1,2 -p PID
# Pause process, send it to the background and disown it, so that it keeps running after closing the shell.
^Z $bg $disown
# Repeat previous command until it exists successfully
until !!; do :; done
# Print every Nth line
function every() { N=$1; S=1; [ "${N:0:1}" = '-' ] && N="${N:1}" || S=0; sed -n "$S~${N}p"; }
# Print all available terminal colors (and codes)
for code in {0..255}; do printf "\[\e[38;05;${code}m $code: Test\n" && echo -e "Code: \[\e[38;05;${code}m $code: "; done
# Search for a <pattern> string inside all files in the current directory
grep -RnisI <pattern> *
#####################
### Generic commands
#####################
# Dump hex/ascii table of a binary file
hexdump -C filename
# List open TCP/UDP connections and commands that are using them (+c 15 flag shows 15 characters, what OS X uses)
lsof +c 50 -r -i TCP -i UDP
# Shut down computer in 45 minutes
sudo shutdown -h +45
# Show apps that use internet connection at the moment
ss -p
# Get PID of processes which have 'filename' open
fuser filename
# KILL PID of processes which have 'filename' open
fuser -k filename
# Run 'long and slow terminal command' when the load is below 0.8 (schedule for a quiet time)
echo "long and slow terminal command" | batch
# Start command and kill it if it doesn't finish before 5 seconds
timeout 5s command
# Show output of COMMAND in the top right corner of the shell, updating every $SECONDS seconds
# This can be used with date (shows a clock!) uptime, or others DOESN'T WORK ON OSX
while true; do echo -ne "\e[s\e[0;$((COLUMNS-27))H$(COMMAND)\e[u"; sleep $SECONDS; done &
# This does the same thing, but uses tput instead of escape codes
while sleep 1;do tput sc;tput cup 0 $(($(tput cols)-29));date;tput rc;done &
#####################
### Mac OS X
#####################
# Configuration:
scutil
configd
# Disk:
diskutil
# Create a RAM disk, the size has to be specified in units of 512-byte sectors,
# to have a 4 GB RAM disk, one has to use ram://8388608, which is the result of (4*(1024^3))/512
diskutil erasevolume HFS+ RAM Disk $(hdiutil attach -nomount ram://2097152)
# CPU Clock/Power info (must be called as superuser)
sudo powermetrics
# Speak:
say "This is just a test."
# Send say output to Airplay (to list available services say -a ?)
say -a "AirPlay" "hello world"
# Copy command output to clipboard:
command_name | pbcopy
# Paste command output:
pbpaste
# Execute applescript
osascript -e osascript
# Play audio files from the command line
afplay fil_ename
# Convert audio files from the command line
afconvert
# Conversion example (to core audio file, caff, from mp3)
afconvert -f caff -d LEI16@22050 Bottle\ Opener.mp3 Bottle\ Opener.caf
# Screensaver as background:
/System/Library/Frameworks/ScreenSaver.framework/Resources/ScreenSaverEngine.app/Contents/MacOS/ScreenSaverEngine -background &
# Change speed of Mission Control Animation (default is 0.24)
defaults write com.apple.dock expose-animation-duration -float 0.24
# Prevent a system from sleeping for one hour
caffeinate -u -t 3600
# Prevent sleep until the process has completed:
caffeinate -s $PROCESS
# Convert any document type to any document type
textutil
# Show filesystem usage by processes:
sudo fs_usage
# Find files created after a timestamp:
touch timestamp
find -x / -newer timestamp
#####################
# File Conversion
#####################
# Convert image size to 100x100
sips -Z 100x100 image.jpg
# Convert image to type png
# (WARNING: this modifies the original file and DOES NOT CHANGE EXTENSION, use --out to specify an output)
sips -s format png test.jpg
# Convert image to jpg and resize (better performance than sips)
mogrify -filter lanczos2 -resize 50% -format jpg -quality 92 -path $output_path
# Convert Audio file (to formats known by CoreAudio)
afconvert track.aiff -o track.m4a -q 127 -b 160000 -f 'm4af' -d 'aac '
#(look up afplay)
## sox, the swiss army knife of audio manipulation (custom installed)
man sox
# Convert any type of (text) file to PDF
cupsfilter file_name > output.pdf
# Create a video from a list of images
# -r gives the framerate, the images are numbered
# the formatting is given by the classic c string formatting
# Output is out.mp4
ffmpeg -r 10 -i image-06d.png -c:v libx264 -vf "fps=25,format=yuv420p" out.mp4
##### SED ####
## The -n option below prints line numbers for the original file
## Use -i [ext] to apply substitution to $filename, ext is the
## extension of the backup file used.
# Print lines between 10 and 20 of $filename
sed [-n|-i [ext]] '10,20p' $filename
# Print line 5 of $filename
sed [-n|-i [ext]] 5p $filename
# Delete line 5 of $filename
sed [-n|-i [ext]] 5d $filename
# Delete lines between 10 and 20 of $filename
sed [-n|-i ''[ext]] '10,20d' $filename
# Delete lines matching foo
sed '/foo/d'
# Delete 5 lines after a pattern (including the line with the pattern):
sed -e '/pattern/,+5d' file.txt
# Delete 5 lines after a pattern (excluding the line with the pattern):
sed -e '/pattern/{n;N;N;N;N;d}' file.txt
# Replace first occurrence of foo with bar
sed 's|foo|bar|'
sed 's/foo/bar/'
sed 's-foo-bar-'
# To replace all occurrences add g (global) before the end of the command:
sed 's/foo/bar/g'
#####################
# Random Stuff
#####################
# ASCII Star Wars
telnet towel.blinkenlights.nl
# Zork-like game
emacs -batch -l dunnet
# BINARY CLOCK!
watch -n 1 'echo "obase=2;`date +%s`" | bc'