Skip to main content

Linux Shell II

Manejo de archivos y directorios

Jerarquía

The Filesystem Hierarchy Standard (FHS) is a reference describing the conventions used for the layout of Unix-like systems. It has been made popular by its use in Linux distributions, but it is used by other Unix-like systems as well

📖 wikipedia

fstab

The fstab file can be used to define how disk partitions, various other block devices, or remote file systems should be mounted into the file system.

$ sudo nvim /etc/fstab

Permisos

Unix-like systems implement three specific permissions that apply to each class:

The read permission grants the ability to read a file. When set for a directory, this permission grants the ability to read the names of files in the directory, but not to find out any further information about them such as contents, file type, size, ownership, permissions.

The write permission grants the ability to modify a file. When set for a directory, this permission grants the ability to modify entries in the directory, which includes creating files, deleting files, and renaming files. This requires that execute is also set; without it, the write permission is meaningless for directories.

The execute permission grants the ability to execute a file. This permission must be set for executable programs, in order to allow the operating system to run them. When set for a directory, the execute permission is interpreted as the search permission: it grants the ability to access file contents and meta-information if its name is known, but not list files inside the directory, unless read is set also.

📖 wikipedia

sshfs

SSHFS is a FUSE-based file system client for mounting remote directories over a Secure Shell connection.

$ sshfs [user@]host:[dir] mountpoint [options]

Enviroment variables

An environment variable is a named object that contains data used by one or more applications. In simple terms, it is a variable with a name and a value. The value of an environmental variable can for example be the location of all executable files in the file system, the default editor that should be used, or the system locale settings. Users new to Linux may often find this way of managing settings a bit unmanageable. However, environment variables provide a simple way to share configuration settings between multiple applications and processes in Linux.

📖 arch wiki

Crear una variable e imprimirla:

$ VAR='Hola mundo!'
$ echo VAR
VAR
$ echo $VAR
Hola mundo!

Para ver el contenido de una variable debemos anteceder su nombre con el signo $. Podemos utilizar el comando echo para imprimir el su valor.

El comando printenv nos muestra las variables definidas en nuestra sesión, para crear una variable en nuestro entorno actual utilizamos el comando export y si queremos que esa variable este siempre presente en nuestro shell la debemos declarar en nuestro archivo de configuración, por ejemplo .bash:profile o zshenv

El comando env nos permite ejecutar un programa en un enviroment modificado temporalmente, por ejemplo:

env VAR=prueba kitty

de esta forma ejecutaremos la terminal kitty con un enviroment que contenga la variable VAR definida como "prueba":

$ echo $VAR
prueba

PATH

PATH contains a colon-separated list of directories in which your system looks for executable files. When a regular command (e.g. ls, systemctl or pacman) is interpreted by the shell (e.g. bash or zsh), the shell looks for an executable file with the same name as your command in the listed directories, and executes it. To run executables that are not listed in PATH, a relative or absolute path to the executable must be given, e.g. ./a.out or /bin/ls.

echo $PATH
/home/user/bin:/usr/bin:/usr/local/bin

El comando which nos permite encontrar un ejecutable en nuestro sistema.

Which takes one or more arguments. For each of its arguments it prints to stdout the full path of the executables that would have been executed when this argument had been entered at the shell prompt. It does this by searching for an executable or script in the directories listed in the environment variable PATH using the same algorithm as bash(1).

alias

In computing, alias is a command in various command-line interpreters (shells), which enables a replacement of a word by another string.[1] It is mainly used for abbreviating a system command, or for adding default arguments to a regularly used command.

📖 wikipedia

Los alias pueden ser creados simplemente asignando un valor o nombre a otra orden. Un ejemplo en el intérprete Bash sería:

alias copy="cp"

Para ver qué alias están definidos los siguientes comandos pueden ser utilizados:

alias          # Usado sin argumentos; muestra una lista de los alias actuales

Si queremos que nuestros alias estén siempre disponibles al abrir nuestro shell, hay que declararlos en nuestro archivo de configuración, por ejemplo bashrc.

Configuración (dotfiles)

In Unix-like operating systems, any file or folder that starts with a dot character (for example, /home/user/.config), commonly called a dot file or dotfile, is to be treated as hidden – that is, the ls command does not display them unless the -a or -A flags (ls -a or ls -A) are used.

Para poder ver los archivos ocultos podemos usar la opcion ls -a o su versión larga ls --all.

A convention arose of using dotfiles in the user's home directory to store per-user configuration or informational text. Early uses of this were the well-known dotfiles .profile, .login, and .cshrc, which are configuration files for the Bourne shell and C shell and shells compatible with them

Many applications, from bash to desktop environments such as GNOME, now store their per-user configuration this way, but the Unix/Linux freedesktop.org XDG Base Directory Specification aims to migrate user config files from individual dotfiles in $HOME to non-hidden files in the hidden directory $HOME/.config.

📖 wikipedia

User-specific application configuration is traditionally stored in so called dotfiles (files whose filename starts with a dot). It is common practice to track dotfiles with a version control system such as Git to keep track of changes and synchronize dotfiles across various hosts.

📖 arch wiki

Utilizar un repositorio git para guardar nuestros archivos de configuración es una opción muy común y nos facilita la configuración de diferentes ordenadores. Una herramienta muy útil para este propósito es GNU stow

GNU Stow is a symlink farm manager which takes distinct packages of software and/or data located in separate directories on the filesystem, and makes them appear to be installed in the same place.

fzf

In computer science, approximate string matching (often colloquially referred to as fuzzy string searching) is the technique of finding strings that match a pattern approximately (rather than exactly). The problem of approximate string matching is typically divided into two sub-problems: finding approximate substring matches inside a given string and finding dictionary strings that match the pattern approximately.

📖 wikipedia

fzf is a general-purpose command-line fuzzy finder. It's an interactive Unix filter for command-line that can be used with any list; files, command history, processes, hostnames, bookmarks, git commits, etc.

📖 repo de fzf

Ejemplos:

ls | fzf
ps ax | grep fzf
cd "$(ls | fzf)"
kill -9 "$(ps ax | fzf)"

Ejemplo

alias pacs='pacman -Slq | fzf --multi --preview '\''pacman -Si {1}'\'' | xargs -ro sudo pacman -S'

En este ejemplo creamos un alias que incluye varias redirecciones y utiliza fzf para seleccionar un paquete a instalar:

  1. pacman -Slq: lista todos los paquetes disponibles.
  2. fzf --multi --preview: Nos permite seleccionar uno o varios paquetes con fzf.
    • La opción --multi: Enable multi-select with tab/shift-tab. It optionally takes an integer argument which denotes the maximum number of items that can be selected.
    • La opción --preview: Execute the given command for the current line and display the result on the preview window. in the command is the placeholder that is replaced to the single-quoted string of the current line.
    • pacman -Si {1}: genera la información para el preview del paquete donde tenemos el cursor.
  3. xargs -ro: Ejecuta el comando indicado con los parámteros que recibe desde stdinput.
    • La opción -r: (--no-run-if-empty) If the standard input does not contain any nonblanks, do not run the command. Normally, the command is run once even if there is no input. This option is a GNU extension.
    • La opción -o: (--open-tty) Reopen stdin as /dev/tty in the child process before executing the command. This is useful if you want xargs to run an interactive application.
    • sudo pacman -S: Instala el paquete seleccionado ustilizando sudo.

Regular Expressions

A regular expression (shortened as regex or regexp), sometimes referred to as rational expression, is a sequence of characters that specifies a match pattern in text. Usually such patterns are used by string-searching algorithms for "find" or "find and replace" operations on strings, or for input validation. Regular expression techniques are developed in theoretical computer science and formal language theory.

📖 wikipedia

recursos

Learn Regular Expressions on regexone.com
Test regex on ihateregex.io
or Learn Regex step by step on regexlearn.com