Ambos lados, revisión anterior
Revisión previa
Próxima revisión
|
Revisión previa
|
es:howtos:general_admin:cli_constructs_and_useful_info [2019/02/07 15:25 (UTC)] slackwarespanol [CLI constructs and useful info] |
es:howtos:general_admin:cli_constructs_and_useful_info [2019/02/07 20:09 (UTC)] slackwarespanol |
<!-- Add your text below. We strongly advise to start with a Headline (see button bar above). --> | <!-- Add your text below. We strongly advise to start with a Headline (see button bar above). --> |
<note warning>En proceso de traducción. Victor</note> | ====== Construcciones de CLI (Interfaz de línea de comandos) e información útil ====== |
====== Construcciones de CLI e información útil ====== | El propósito de este artículo no es ser un tutorial de CLI, sino más bien ser una exposición de construcciones comunes utilizadas en shell scripting para lograr un objetivo de manera eficiente. También hay secciones que simplemente ayudan a entender un tema determinado. |
// El propósito de este artículo no es ser un tutorial de CLI, sino más bien ser una exposición de construcciones comunes utilizadas en shell scripting para lograr un objetivo de manera eficiente. También hay secciones que simplemente ayudan a entender un tema determinado. | ==== Construye ==== |
==== Constructs ==== | |
=== rev | cut | rev === | === rev | cut | rev === |
It is often useful to reverse a string and then use cut. For example, take a Slackware package and get its name: | A menudo es útil revertir una cadena y luego usar cut. Por ejemplo, tome un paquete Slackware y obtenga su nombre: |
<code bash> | <code bash> |
echo dejavu-fonts-ttf-2.33-noarch-1 | rev | cut -d - -f 1-3 --complement | rev | echo dejavu-fonts-ttf-2.33-noarch-1 | rev | cut -d - -f 1-3 --complement | rev |
ls -1 /var/log/packages | rev | cut -d - -f 1-3 --complement | rev | ls -1 /var/log/packages | rev | cut -d - -f 1-3 --complement | rev |
</code> | </code> |
Or if you wanted to get the full path of a file, minus the suffix. | O si desea obtener la ruta completa de un archivo, menos el sufijo. |
<code bash> | <code bash> |
echo /proc/config.gz | rev | cut -d. -f1 --complement | rev | echo /proc/config.gz | rev | cut -d. -f1 --complement | rev |
</code> | </code> |
=== replace a suffix === | === Reemplazar un sufijo === |
Say you wanted to make a video conversion script, and you needed to change the suffix. | Digamos que querías hacer un script de conversión de video y que necesitabas cambiar el sufijo. |
<code bash> | <code bash> |
input=test.mkv | input=test.mkv |
</code> | </code> |
=== find | xargs === | === find | xargs === |
This is a special interaction between find and xargs that allows one to deal with spaces in file names. It is very fast because many commands like ''rm'', ''rmdir'', and ''shred'' take multiple file inputs on the command line. A generic construct is something like: | Esta es una interacción especial entre find y xargs que permite tratar espacios en los nombres de archivos. Es muy rápido porque muchos comandos como '' rm '', '' rmdir '' y '' shred '' toman múltiples entradas de archivos en la línea de comandos. Una construcción genérica es algo como: |
<code bash> | <code bash> |
find . -type f -print0 | xargs -0 "$command" | find . -type f -print0 | xargs -0 "$command" |
</code> | </code> |
You can replace ''$command'' with whatever command you need to run on the files as long as it supports multiple file input. If you have a list of files you can still preserve spaces: | Puede reemplazar '' $ command '' con cualquier comando que necesite para ejecutar en los archivos siempre que sea compatible con la entrada de múltiples archivos. Si tiene una lista de archivos, aún puede conservar espacios: |
<code bash> | <code bash> |
tr '\n' '\0' < "$file" | xargs -0 "$command" | tr '\n' '\0' < "$file" | xargs -0 "$command" |
</code> | </code> |
=== comm before and after === | === comm antes y después === |
This construct is useful for package management applications. From the comm man page: | Esta construcción es útil para aplicaciones de gestión de paquetes. Desde la página de manual de comm: |
<code> | <code> |
With no options, produce three-column output. | With no options, produce three-column output. |
column three contains lines common to both files. | column three contains lines common to both files. |
</code> | </code> |
The options ''-1'' ''-2'' ''-3'' suppress the respective columns. Say you wanted to log files that were added to ''/usr'' after running command ''$1'': | Las opciones '' '-1' '' '' '-2' '' '' '-3''' suprimen las columnas respectivas. Supongamos que desea registrar los archivos que se agregaron a '' /usr'' después de ejecutar el comando '' $ 1 '': |
<code bash> | <code bash> |
# before, make install, after | # before, make install, after |
comm -13 "$tmp/before-sorted" "$tmp/after-sorted" > "$log/$name" | comm -13 "$tmp/before-sorted" "$tmp/after-sorted" > "$log/$name" |
</code> | </code> |
Note that comm requires sorted files. Here ''-1'' suppresses lines unique to before, ''-3'' suppresses lines present in both files, so you are left with column 2 which contains files unique to after i.e. the files added. Many people would like to use diff to compare files, but it's mostly for creating patches. | |
| Tenga en cuenta que comm requiere archivos ordenados. Aquí '' -1 '' suprime las líneas exclusivas de antes, '' -3 '' suprime las líneas presentes en ambos archivos, por lo que queda con la columna 2 que contiene archivos exclusivos después de los archivos agregados. A muchas personas les gustaría usar diff para comparar archivos, pero es principalmente para crear parches. |
=== while read line === | === while read line === |
This construct is common and is useful for reading files or stdin one line at a time. Here is an example that can be used to concatenate split files in order: | Esta construcción es común y es útil para leer archivos o ingresar una línea a la vez. Aquí hay un ejemplo que se puede usar para concatenar archivos divididos en orden: |
<code bash> | <code bash> |
base="$(echo "$@" | rev | cut -d. -f1 --complement | rev)" | base="$(echo "$@" | rev | cut -d. -f1 --complement | rev)" |
done | done |
</code> | </code> |
Also note that ''sort -V'' is a version sort and is useful in cases where ''ls'' sorts suffixes incorrectly. The usual way to prevent this is to name numbered suffixes with ''0'' padding like ''file.001'', but it may overflow and this is why ''sort -V'' is useful. | También tenga en cuenta que '' sort -V '' es una clasificación de versión y es útil en los casos en que '' ls '' ordena los sufijos de forma incorrecta. La forma habitual de evitar esto es nombrar sufijos numerados con '' 0 '' como '' file.001 '', pero puede desbordarse y es por eso que '' sort -V '' es útil. |
=== for i in === | === for i in === |
Here is an example for extracting all rpms in a directory: | Aquí hay un ejemplo para extraer todos los rpms en un directorio: |
<code bash> | <code bash> |
for i in *.rpm | for i in *.rpm |
done | done |
</code> | </code> |
You can also use ''seq'' to make ''i'' a loop counter: | También puede usar '' seq '' para hacer que '' i '' sea un contador de bucle: |
<code bash> | <code bash> |
for i in $(seq 1 100) | for i in $(seq 1 100) |
done | done |
</code> | </code> |
Note that there are no quotes around ''$(seq)'' because otherwise it would quote the entire expanded number sequence and that wouldn't work right. | Tenga en cuenta que no hay comillas alrededor de '' $ (seq) '' porque de lo contrario, citaría la secuencia numérica completa y eso no funcionaría bien. |
== External Links === | == Enlaces externos === |
* http://www.commandlinefu.com/commands/browse | * http://www.commandlinefu.com/commands/browse |
==== Quoting ==== | ==== Comilla ==== |
Quoting may seem complicated, and reasons for it obscure, but there is a purpose to it and it is not that complicated. | Las comillas pueden parecer complicadas, y las razones de ello son oscuras, pero tiene un propósito y no es tan complicado. |
=== Double quoting === | === Doble comillas === |
The reason for double quoting is to preserve spaces, like spaces in file names. Double quoting a variable or command substitution makes it into a single argument. An example: | La razón para la comilla doble es para preservar espacios, como espacios en nombres de archivos. La doble cita de una variable o una sustitución de comando lo convierte en un solo argumento. Un ejemplo: |
<code bash> | <code bash> |
bash-4.2$ ls | bash-4.2$ ls |
bash-4.2$ | bash-4.2$ |
</code> | </code> |
Clearly you need to quote a file with spaces. You could use single quotes here, because no variables were inside the quotes. You should not quote in this case: | Claramente necesitas encomillar un archivo con espacios. Puede usar comillas simples aquí, porque no hay variables dentro de las comillas. No debes encomillar en este caso: |
<code bash> | <code bash> |
bash-4.2$ for i in $(seq 1 10); do printf "$i "; done; echo; | bash-4.2$ for i in $(seq 1 10); do printf "$i "; done; echo; |
bash-4.2$ | bash-4.2$ |
</code> | </code> |
Nor should you quote in any case where a command requires multiple variables and you give them to it inside one quoted variable. A quoted variable is then taken as the only argument, rather than multiple arguments. An example: | Tampoco debe encomillar en ningún caso en que un comando requiera múltiples variables y se las asigne dentro de una variable encomillada. Una variable encomillada se toma entonces como el único argumento, en lugar de múltiples argumentos. Un ejemplo: |
<code> | <code> |
bash-4.2$ ls | bash-4.2$ ls |
bash-4.2$ | bash-4.2$ |
</code> | </code> |
Also note that you can and should quote within command substitutions, as shown by the ''replace a suffix'' example above and: | También tenga en cuenta que puede y debe encomillar dentro de las sustituciones de comandos, como se muestra en el ejemplo anterior "reemplazar un sufijo" y: |
<code bash> | <code bash> |
mkdir "$(basename "$(pwd)")" | mkdir "$(basename "$(pwd)")" |
</code> | </code> |
This makes a directory within the current directory called the same name as the current directory. If ''pwd'' expands into something with spaces, the command will work. | Esto crea un directorio dentro del directorio actual llamado el mismo nombre que el directorio actual. Si '' pwd '' se expande en algo con espacios, el comando funcionará. |
=== Single quoting === | === Comilla simple === |
The reason for single quoting is to escape special characters from the shell, while passing them to a command so it can use them. You should use single quotes for every argument passed to another program that contains shell characters to be interpreted by that program and **NOT** by the shell. Example: | La razón para la comilla simple es para escapar caracteres especiales de la shell, mientras se los pasa a un comando para que pueda usarlos. Debe usar comillas simples para cada argumento pasado a otro programa que contenga caracteres de shell para que sean interpretados por ese programa y ** NO ** por el shell. Ejemplo: |
<code bash> | <code bash> |
bash-4.2$ find -name *.txt | bash-4.2$ find -name *.txt |
bash-4.2$ | bash-4.2$ |
</code> | </code> |
Here the shell expands ''*'' before find sees it. You should single quote input to ''awk'', ''find'', ''sed'', and ''grep'', as each of these uses special characters that overlap with the shells', and thus they must be protected from shell expansion. | Aquí el sehell se expande '' * '' antes de encontrarla. Debe ingresar la entrada de comillas a '' awk '', '' find '', '' sed '' y '' grep '', ya que cada uno de ellos utiliza caracteres especiales que se superponen con las del shell, y por lo tanto deben ser Protegido de la expansión del shell. |
=== External Links === | === Enlaces externos === |
* http://www.grymoire.com/Unix/Quote.html | * http://www.grymoire.com/Unix/Quote.html |
==== Regular expressions ==== | ==== Expresiones regulares ==== |
=== Basic === | === Básico === |
* ''.'' matches any single character. | * ''. '' coincide con cualquier carácter individual. |
* ''\'' escapes the next character. | * '' \ '' evita del siguiente carácter. |
<note>Remember to escape the ''.'' using ''\.'' if you want an actual ''.'' | <note>Recuerde que debe evitar ''. '' usando '' \. '' Si quieres un verdadero ''. '' |
<code> | <code> |
bash-4.2$ cat test.txt | bash-4.2$ cat test.txt |
test | test |
</code></note> | </code></note> |
* ''[]'' is a class and matches anything inside the brakets for a single character. Examples: | |
* ''[Yy]'' matches Y or y. | * '' [ ] '' es una clase y combina cualquier cosa dentro de los corchetes para un solo personaje. Ejemplos: |
* ''[a-z0-9]'' includes a range, and in this case matches a through z and 0 through 9. | * '' [Yy] '' coincide con Y o y. |
* ''[^a-z]'' negates the range, so in this case it matches anything but a through z. | * '' [a-z0-9] '' incluye un rango, y en este caso coincide con a a través de z y de 0 a 9. |
* ''^'' matches the beginning of a line. Example: ''^a'' matches an a at the beginning of a line. | * '' [^ a-z] '' niega el rango, por lo que, en este caso, se ajusta a cualquier cosa excepto a a z. |
* ''$'' matches the end of a line. Example: ''a$'' matches an a at the end of a line. | * '' ^ '' coincide con el principio de una línea. Ejemplo: '' ^ a '' coincide con una a al principio de una línea. |
* ''\<'' matches the beginning of a word. Example: ''\<a'' matches an a at the beginning of a word. | * '' $ '' coincide con el final de una línea. Ejemplo: '' a $ '' coincide con una a al final de una línea. |
* ''\>'' matches the end of a word. Example: ''a\>'' matches an a at the end of a word. | * '' \ <'' coincide con el principio de una palabra. Ejemplo: '' \ <a '' coincide con una a al principio de una palabra. |
* Example: ''\<[tT]he\>'' matches the word ''the'' or ''The''. | * '' \> '' coincide con el final de una palabra. Ejemplo: '' a \> '' coincide con una a al final de una palabra. |
* ''*'' matches any number of the previous character or nothing = no character. Example: ''[0-9]*'' which will match any number of numbers. ''.*'' matches any number of anything. | * Ejemplo: '' \ <[tT] he \> '' coincide con la palabra '' el '' o '' El ''. |
=== Extended regular expressions === | * '' * '' coincide con cualquier número del carácter anterior o nada = ningún carácter. Ejemplo: '' [0-9] * '' que coincidirá con cualquier número de números. ''. * '' coincide con cualquier número de cualquier cosa. |
The following must be supported by the program for them to work. For example for grep you must run ''egrep'' or ''grep -E''. | === Expresiones regulares extendidas === |
* ''+'' matches any number of the previous character, like ''*'', but there must be at least one to match, so it will not match nothing or no character. | |
* ''?'' makes the previous character optional (it can be missing), and is matched at most once. | El programa debe admitir lo siguiente para que funcionen. Por ejemplo, para grep debe ejecutar '' egrep '' o '' grep -E ''. |
* ''(|)'' acts like an OR statement. Example: ''(it|her|this)'' matches any of those words. | |
* ''a{3}'' matches ''aaa'' = 3 a's. | * '' + '' coincide con cualquier número del carácter anterior, como '' * '', pero debe haber al menos uno para que coincida, por lo que no coincidirá con nada o ningún carácter. |
* ''a{4,8}'' matches an a at least 4 times and at max 8 times, so ''aaaa'', ''aaaaa'', ''aaaaaa'', ''aaaaaaa'', and ''aaaaaaaa''. | * ''? '' hace que el carácter anterior sea opcional (puede faltar), y se compara como máximo una vez. |
* ''{0,}'' = ''*'' | * '' (|) '' actúa como una declaración OR. Ejemplo: '' (it | her | this) '' coincide con cualquiera de esas palabras. |
* ''{1,}'' = ''+'' | * '' a {3} '' coincide con '' aaa '' = 3 a's. |
* ''{,1}'' = ''?'' | * '' a {4,8} '' coincide con a al menos 4 veces y como máximo 8 veces, por lo que '' aaaa '', '' aaaaa '', '' aaaaaa '', '' aaaaaaa '' y '' aaaaaaaa ''. |
=== External Links === | * '' {0,} '' = '' * '' |
| * '' {1,} '' = '' + '' |
| * '' {, 1} '' = ''? '' |
| === Enlaces externos === |
* http://www.grymoire.com/Unix/Regular.html | * http://www.grymoire.com/Unix/Regular.html |
* http://www.regular-expressions.info/ | * http://www.regular-expressions.info/ |
==== Useful commands and info ==== | ==== Comandos útiles e información ==== |
=== stat === | === stat === |
Stat is the most accurate way to determine: | Stat es la forma más precisa de determinar: |
* File size in bytes: <code bash>stat -c '%s' file.txt</code> | * Tamaño del archivo en bytes:<code bash>stat -c '%s' file.txt</code> |
* File permissions in octal: <code bash>stat -c '%a' file.txt</code> | * Permisos de archivos en octal: <code bash>stat -c '%a' file.txt</code> |
=== awk variable defaults === | === awk variable por defecto === |
An important point is that awk variables are set to zero by default. This may cause problems in some situtations. Example: | Un punto importante es que las variables awk se establecen en cero de forma predeterminada. Esto puede causar problemas en algunas situaciones. Ejemplo: |
<code bash> | <code bash> |
echo -ne '-321\n-14\n-1\n-34\n-4\n' | awk 'BEGIN{max=""}{if ($1 > max) max=$1; if ($1 < min) min=$1;}END{print min"\t"max}' | echo -ne '-321\n-14\n-1\n-34\n-4\n' | awk 'BEGIN{max=""}{if ($1 > max) max=$1; if ($1 < min) min=$1;}END{print min"\t"max}' |
</code> | </code> |
This works properly because max is set to an empty string and thus has a lower value than any number. Try removing the BEGIN clause and see what happens. Also note that adding ''min=""'' to the BEGIN clause fails as well. | Esto funciona correctamente porque max se establece en una cadena vacía y, por lo tanto, tiene un valor más bajo que cualquier número. Intenta eliminar la cláusula BEGIN y ver qué pasa. También tenga en cuenta que la adición de '' min = "" '' a la cláusula BEGIN también falla. |
=== no data directory test === | |
You can use this to test if a directory contains no data. For example, it will say ''0'' if the directory only contains empty files and directories = no data. | === no hay prueba de directorio de datos === |
| |
| Puede usar esto para probar si un directorio no contiene datos. Por ejemplo, dirá '' 0 '' si el directorio solo contiene archivos vacíos y directorios = sin datos. |
<code bash> | <code bash> |
du -s directory | du -s directory |
</code> | </code> |
=== cmp === | === cmp === |
This can compare two files byte by byte, and can be more useful than checksums. For example, after you burn a CD/DVD, you can run: | Esto puede comparar dos archivos byte a byte, y puede ser más útil que las sumas de comprobación. Por ejemplo, después de grabar un CD / DVD, puede ejecutar: |
<code bash> | <code bash> |
cmp slackware.iso /dev/sr0 | cmp slackware.iso /dev/sr0 |
</code> | </code> |
It should say the following if the disk burned correctly: | Debe decir lo siguiente si el disco se quemó correctamente: |
<code bash> | <code bash> |
cmp: EOF on slackware.iso | cmp: EOF on slackware.iso |
</code> | </code> |
=== shell math === | === shell matemáticas === |
Remember that shell utilities like ''let'' and ''expr'' only do integer math. For floating point use either ''bc'' or ''awk''. | Recuerde que las utilidades de shell como '' let '' y '' expr '' solo hacen matemáticas enteras. Para el punto flotante, use '' bc '' o '' awk ''. |
=== shell GUI === | === shell GUI === |
There are numerous programs that allow you to create GUIs from a shell script. | Existen numerosos programas que le permiten crear GUI desde un script de shell. |
* [[http://xdialog.free.fr/|Xdialog is fully dialog compatible.]] | * [[http://xdialog.free.fr/|Xdialog is fully dialog compatible.]] |
* [[https://sites.google.com/site/easybashgui/home|A function library that increases shell GUI portability.]] | * [[https://sites.google.com/site/easybashgui/home|A function library that increases shell GUI portability.]] |
* [[http://code.google.com/p/gtkdialog/|Gtkdialog has advanced features for customized GUIs.]] | * [[http://code.google.com/p/gtkdialog/|Gtkdialog has advanced features for customized GUIs.]] |
=== External Links === | === Enlaces externos === |
* [[http://www.grymoire.com/Unix/|Guide to awk, bash, sed, find, and more]] | * [[http://www.grymoire.com/Unix/|Guide to awk, bash, sed, find, and more]] |
* [[http://www.tldp.org/LDP/abs/html/index.html|Advanced bash guide]] | * [[http://www.tldp.org/LDP/abs/html/index.html|Advanced bash guide]] |
<!-- * Originally written by [[wiki:user:xxx | User X]] --> | <!-- * Originally written by [[wiki:user:xxx | User X]] --> |
<!-- * Contributions by [[wiki:user:yyy | User Y]] --> | <!-- * Contributions by [[wiki:user:yyy | User Y]] --> |
* I quoted ''man comm'' | * Cité ''man comm'' |
* I used ''man grep'' for the regex section. | * Usé '' man grep '' para la sección de expresiones regulares. |
* Written by [[wiki:user:htexmexh|H_TeXMeX_H]] | * Escrito por [[wiki:user:htexmexh|H_TeXMeX_H]] |
| * Traducido por: [[wiki:user: slackwarespanol | Victor]] 2019/02/07 20:04 (UTC) |
<!-- Please do not modify anything below, except adding new tags.--> | <!-- Please do not modify anything below, except adding new tags.--> |
<!-- You must remove the tag-word "template" below before saving your new page --> | <!-- You must remove the tag-word "template" below before saving your new page --> |
{{tag>howtos software author_htexmexh}} | {{tag>howtos software author_htexmexh}} |