Skip to content

Instantly share code, notes, and snippets.

@chiguiredev
Created August 1, 2020 15:22
Show Gist options
  • Save chiguiredev/9d19372fba5dd5bc522bd0bb02291536 to your computer and use it in GitHub Desktop.
Save chiguiredev/9d19372fba5dd5bc522bd0bb02291536 to your computer and use it in GitHub Desktop.

Terminal-fu

Cómo ser eficiente en la terminal de linux

En esta guia aprenderas a aprovechar la herramientas disponibles en la terminal de linux y en los paquetes de tu distribución favorita para lograr ser ágil al momento de querer realizar alguna tarea en la línea de comandos, en este tutorial

Actualizando nuestro sistema operativo

Para este tutorial estaremos utilizando Manjaro que es una distribución de linux basada en Arch, por lo tanto utiliza el gestor de paquetes pacman utilizaremos el siguiente comando en la consola sudo pacman -Syyu y vamos aceptar las actualizaciones

Instalando la consola Alacritty (opcional)

Alacritty es un emulador de consola escrito en rust, es uno de las consolas más rápida que existen y esto se debe a que hace uso de la tarjeta gráfica de tu computador para mejorar el rendimiento en el renderizado de contenido de la consola si quieres conocer más puedes revisar su repositorio en github (https://github.com/alacritty/alacritty); para instalarla simplemente necesitas el siguiente comando:

sudo pacman -S alacritty

Para hacer que nuestra consola sea más estética y se vea más limpia vamos a instalar un tema en este caso el tema dracula, para esto vamos a copiar el contenido del siguiente archivo (https://github.com/dracula/alacritty/blob/master/dracula.yml) en la ruta ~/.config/alacritty/alacritty.yml

Configurando ZSH + oh-my-zsh

Que es un shell? es una interfaz de usuario que nos permite acceder a los servicios de un sistema operativo, principalmente a los ejecutables que están instalados en este sistema operativo.

Zsh es un shell más avanzado que bash que nos permite tener configuraciones que facilitan nuestro trabajo cuando estamos haciendo tareas en la consola, lo primero que debemos hacer es instalarlo par esto usaremos el comando sudo pacman -S zsh. Una vez instalado tendremos que configurarlo para que sea nuestro shell predeterminado para esto seguimos los siguientes pasos:

  • Obtener la dirección en el sistema de archivos del ejecutable de zsh con el comando which zs
  • Cambiarlo a que sea nuestro shell por defecto con el comando chsh -s /usr/bin/zsh luego de esto nos salimos de nuestra sesión de usuario y nos volvemos a loguear, es importante no correr este comando con sudo, si lo corremos con sudo estamos cambiando el shell del superusuario a zsh
  • En la siguiente vez que iniciemos nuestra consola vamos a ver la siguiente pantalla, donde zsh nos pregunta que deseamos hacer con nuestros archivos de configuración, vamos a seleccionar la opción (0) que nos va a crear un archivo con un comentario

ZSH plugins

Todos los plugins (https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/)

Para activar estos plugins debemos modificar nuestro archivos de configuración ~/.zshrc

Debemos agregarlo a nuestra lista de plugins:

plugins=(git extract npm docker tmux z)

# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
export TERM="xterm-256color"
export EDITOR="nvim"

source ~/.zplug/init.zsh
#zplug plugins
zplug "dracula/zsh", as:theme

# Path to your oh-my-zsh installation.
export ZSH="/home/rafael/.oh-my-zsh"

# Set name of the theme to load --- if set to "random", it will
# load a random theme each time oh-my-zsh is loaded, in which case,
# to know which specific one was loaded, run: echo $RANDOM_THEME
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="typewritten"

# Set list of themes to pick from when loading at random
# Setting this variable when ZSH_THEME=random will cause zsh to load
# a theme from this variable instead of looking in $ZSH/themes/
# If set to an empty array, this variable will have no effect.
# ZSH_THEME_RANDOM_CANDIDATES=( "robbyrussell" "agnoster" )

# 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 automatically update without prompting.
# DISABLE_UPDATE_PROMPT="true"

# Uncomment the following line to change how often to auto-update (in days).
# export UPDATE_ZSH_DAYS=13

# Uncomment the following line if pasting URLs and other text is messed up.
# DISABLE_MAGIC_FUNCTIONS=true

# 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.
# You can set one of the optional three formats:
# "mm/dd/yyyy"|"dd.mm.yyyy"|"yyyy-mm-dd"
# or set a custom format using the strftime function format specifications,
# see 'man strftime' for details.
# HIST_STAMPS="mm/dd/yyyy"

# Would you like to use another custom folder than $ZSH/custom?
# ZSH_CUSTOM=/path/to/new-custom-folder

# Which plugins would you like to load?
# Standard plugins can be found in $ZSH/plugins/
# Custom plugins may be added to $ZSH_CUSTOM/plugins/
# Example format: plugins=(rails git textmate ruby lighthouse)
# Add wisely, as too many plugins slow down shell startup.
plugins=(git extract npm docker github tmux z zsh-autosuggestions)

source $ZSH/oh-my-zsh.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"

# Set personal aliases, overriding those provided by oh-my-zsh libs,
# plugins, and themes. Aliases can be placed here, though oh-my-zsh
# users are encouraged to define aliases within the ZSH_CUSTOM folder.
# For a full list of active aliases, run `alias`.
#
# Example aliases
# alias zshconfig="mate ~/.zshrc"
# alias ohmyzsh="mate ~/.oh-my-zsh"
alias vim="nvim"

# z and fzf for the win
# shamelessly taken from fzf github page, u sing z to print opened directories
# and fzf to searh the list and cd into it

unalias z 2> /dev/null
z() {
  [ $# -gt 0 ] && _z "$*" && return
  cd "$(_z -l 2>&1 | fzf --nth 2.. --inline-info +s --tac --query "${*##-* }" | sed 's/^[0-9,.]* *//')"
}

# tabtab source for yarn package
# uninstall by removing these lines or running `tabtab uninstall yarn`
[[ -f /home/rafael/.config/yarn/global/node_modules/tabtab/.completions/yarn.zsh ]] && . /home/rafael/.config/yarn/global/node_modules/tabtab/.completions/yarn.zsh

# tm - create new tmux session, or switch to existing one. Works from within tmux too. (@bag-man)
# `tm` will allow you to select your tmux session via fzf.
# `tm irc` will attach to the irc session (if it exists), else it will create it.

tm() {
  [[ -n "$TMUX" ]] && change="switch-client" || change="attach-session"
  if [ $1 ]; then
    tmux $change -t "$1" 2>/dev/null || (tmux new-session -d -s $1 && tmux $change -t "$1"); return
  fi
  session=$(tmux list-sessions -F "#{session_name}" 2>/dev/null | fzf --exit-0) &&  tmux $change -t "$session" || echo "No sessions found."
}

# fe [FUZZY PATTERN] - Open the selected file with the default editor
#   - Bypass fuzzy finder if there's only one match (--select-1)
#   - Exit if there's no match (--exit-0)
fe() {
  local files
  IFS=$'\n' files=($(fzf-tmux --query="$1" --multi --select-1 --exit-0))
  [[ -n "$files" ]] && ${EDITOR:-vim} "${files[@]}"
}

# Modified version where you can press
#   - CTRL-O to open with `open` command,
#   - CTRL-E or Enter key to open with the $EDITOR
fo() {
  local out file key
  IFS=$'\n' out=($(fzf-tmux --query="$1" --exit-0 --expect=ctrl-o,ctrl-e))
  key=$(head -1 <<< "$out")
  file=$(head -2 <<< "$out" | tail -1)
  if [ -n "$file" ]; then
    [ "$key" = ctrl-o ] && open "$file" || ${EDITOR:-nvim} "$file"
  fi
}

[ -f ~/.fzf.zsh ] && source ~/.fzf.zsh

export N_PREFIX="$HOME/n"; [[ :$PATH: == *":$N_PREFIX/bin:"* ]] || PATH+=":$N_PREFIX/bin"  # Added by n-install (see http://git.io/n-install-repo).

Instalando y configurando Tmux

Tmux es un multiplexor de la terminal, si ya se que da miedo la palabra multiplexor, pero básicamente es una forma de decir que podemos conectarnos a diferentes consolas a través de una sola, tmux nos permite tener una sola consola con muchas sesiones y navegar en estas fácilmente a diferencia de tener 5 o 6 ventanas abiertas de la terminal y que sea difícil mantener el orden entre ellas. Además es un programa muy liviano que esta en los repositorios oficiales de la mayoría de las distribuciones de linux y funciona tambien en servidores ya que es un programa basado en la consola.

Incluso nos permite tener sesiones abierta en background y conectarnos y desconectarnos de ellas cuando tengamos la necesidad, podemos dejar todas las sesiones corriendo y cerrar la consola sin preocuparnos de perder el trabajo que ya teníamos.

Para instalar tmux simplemente debes correr el comando sudo pacman -S tmux

Como funciona tmux, tienes sesiones que se pueden generalizar como el primer primitivo de tmux, es decir el bloque principal de la experiencia del uso diario de esta herramienta y cada una de estas sesiones tiene paneles y tabs que te permiten realizar múltiples acciones en una sola sesión de tmux y así por cada una de estas puedes aislar tus necesidades por dominio

# set Zsh as your default Tmux shell
set-option -g default-shell /bin/zsh

#cool colors
# set -g default-terminal "tmux-256color"
set -g default-terminal "tmux-256color"
set -ga terminal-overrides ",*256col*:Tc"

#fixing escape delay issue
set -sg escape-time 0

# automatically renumber tmux windows
set -g renumber-windows on

# quickly open a new window
bind n new-window
bind k confirm kill-window

# Tmux uses a 'control key', let's set it to 'Ctrl-a'
# Reason: 'Ctrl-a' is easier to reach than 'Ctrl-b'
set -g prefix C-a
unbind C-b

# Set the numbering of windows to go from 1 instead
# of 0
set-option -g base-index 1
setw -g pane-base-index 1

# aggressive resizing of the panes after ssh connection with smaller client (phone)
set-window-option -g aggressive-resize

# Allow us to reload our Tmux configuration while using
bind r source-file ~/.tmux.conf \; display "Reloaded!"

# select pane with hjkl
bind -r h select-pane -L
bind -r j select-pane -D
bind -r k select-pane -U
bind -r l select-pane -R

# symbols to split the screen
bind v split-window -h -c '#{pane_current_path}'
bind s split-window -v -c '#{pane_current_path}'

# Enable mouse control
set -g mouse on

# THEME
set -g status-bg colour232
set -g status-fg white
set -g status-interval 30
set -g status-left-length 50
set -g status-left '#{s/root//:client_key_table} #[fg=yellow, bg=colour232] (#S) '
set -g status-right '#[fg=yellow]%d-%m-%Y '
set -g status-justify centre
set-option -g status-position top

FZF

Fzf (fuzzy file finder) es un buscador optimizado para hacer búsquedas muy rápidas a través de un lista de posibles salidas, nos va a permitir movernos muy rápido a través de grandes volúmenes de archivos. Su instalación es muy sencilla solo debemos usar el siguiente comando:

sudo pacman -S fzf

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment