Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

black metal, 07/01/2022, 22:52:17

Guía muy básica con errores


breve
A very brief guide to Linux
C. J. Rennie

5th April 2011

This document is for those who are just beginning with Linux. It covers the really essential commands in some detail, but also gives some
impression of the great scope of commands that are available. It says nothing about email clients, browsers, compilers etc, which are either
documented elsewhere or are sufficiently GUI not to need any documentation such as this.

Logging in and out


You always need to log in by specifying your user name and your password. Once that is done, the Desktop Environment (usually 'Gnome' or
'KDE') starts, and you will be able to do things like open terminal windows, run the file manager, or browse the Internet.

Log off via the menu options provided by the desktop.

To try out the things described in this document it will help to have a 'terminal' window open. How to do this should be obvious from whatever
desktop you are using.

Directories
Sea cual sea su experiencia informática que están ordenados jerárquicamente
Whatever computing background you have, you will be familiar with the concept of directories (or 'folders'), which are arranged hierarchically,
y actúan como contenedores de archivos.
and act as containers for files.

There are between 5 and 10 thousand directories on a Linux machine,


El árbol de directorios está formado por ramas que tienen determinadas funciones.
so it is good to have some idea of how
Los detalles difieren en las distintas versiones de Linux
they are organized. The
pero el nivel superior o directorio 'root' esta siempre
directorydesignado
tree '/'consists ofy contiene
branches having certain functions. The details differ on the various Linux versions, but top level or 'root' directory is
el siguiente directorio
always designated '/', and contains the following directories

Path Function
/suphys/your_name/ For the personal use of users
directorios de datos en otras maquinas
/media/ CD-ROMs, floppies, data directories on other machines
/usr/ Where most programs are located
/bin/ Core operating system programs
/sbin/ Core operating system programs
/etc/ Configuration files for operating system

entre otros.
amongst others.
Las ramas se ordenan aquí de acuerdo a la relevancia para el trabajo diario, así que preocúpate de los primeros, no intentes meterte con los de abajo
The branches are sorted here according to relevance for everyday work, so concern yourself with the first couple do not try to mess with those
De todos modos, se lo impedirán.
near the bottom. (You will be prevented anyway.)
Usted es libre de crear directorios bajo su directorio personal y algunas otras áreas
You are free to create directories under your home directory and certain other areas (e.g., under /media/floppy), while others area may be
protected against modifications. When creating a directory (or file), the names are case-sensitive and you can use spaces — however
spaces are often confusing and annoying (they have to be quoted), and I advise against the practice.
Puede acceder a los directorios especificando su nombre explícitamente dando algún camino que empiece por
You can access directories by specifying their name explicitly (i.e., by giving some path beginning with '/', for example /suphys/chris), or by
o usando acceso directos significa el siguiente directorio hacia arriba
using shortcuts. The shortcuts are as follows: '.' means the current directory; '..' means the next directory up; '~' means your home directory.
Thus '~/data' refers to one of your own directories, 'data', located under your home directory.

Another great help is auto-completion. If you are part-way through typing a path, then pressing the T�� por key will complete the directory or
lo que
filename. If there is ambiguity in how to complete the name, then T�� will just fill in as much as it can, whereupon you can enter another
Repita la operación tantas veces como sea necesario. Si no está seguro de cómo resolver la ambigüedad,
character
puede pulsar
or two to resolve the ambiguity and press T�� again. Repeat as often as necessary. If you are unsure how to resolve the ambiguity,
en cualquier momento para ver cuáles son las alternativas
you can press C���-D at any time to see what the alternatives are.
Si la ruta completa de algún directorio o archivo se imprime en algún lugar de la pantalla, un truco común para utilizar este nombre en un comando es cortar y pegar
Ifresaltar
the full path of some directory or file is printed somewhere on screen, a common trick for using this name in a command is to cut and paste:
el bloque con el botón izquierdo del ratón y arrastrarlo pegarlo con el botón central del ratón
highlight the block with left-click and drag; paste it with middle-click. (This is the Linux equivalent of C���-C and C���-V.) Another way to
highlight is by multiple clicks.
Navegar por los directorios en la línea de comandos no es tan intuitivo como con un navegador gráfico, pero aún así puede hacerse, y de forma sorprendentemente eficiente
Navigating directories on the command line is not as intuitive as with a graphical browser, but can still be done, and done surprisingly
efficiently.

Comandos esenciales
Essential commands
Esta sección ofrece una breve descripciones ilustradas de algunos comandos realmente esenciales Son comandos básicos para tratar con los directorios y archivos
This section gives brief, illustrated descriptions of a few really essential commands. They are basic command for dealing with directories and
files.
Cambia su directorio actual
Change you current directory with cd:

cd .. change to the next directory up → Cambiar al directorio siguiente arriba


cd /usr/bin Change to the directory /usr/bin
cd ~ Change to your home directory

Listing the contents of directories is done with ls:

ls Compact listing of the current directory


ls -l /usr/bin Detailed listing of /usr/bin
ls ~ Compact listing of your home directory
ls -la ~ Detailed listing of your home directory, including those the semi-hidden files beginning with '.'
ls -lt Detailed listing of the current directory, in chronological order

Copying is done with cp:


Copiar un archivo a otro directorio lo que resulta en
cp filename dir Copy a file to some other directory, resulting in dir/filename
Haz una copia, nombrado del archivo especificado
cp filename newname Make a copy, named newname, of the specified file
Copiar todos los archivos con nombres que coincidan
cp something* dir Copy all files with names matching something* to the directory dir
Copie todos los archivos y subdirectorios en a un nuevo directorio
cp -r dir1 dir2 Copy all files and subdirectories in dir1 to a new directory dir2/dir1
Copie todos los archivos y subdirectorios en en el directorio existente
cp -r dir1/* dir2 Copy all files and subdirectories in dir1 into the existing directory dir2
sutil pero importante diferencia entre copiar de
Note the subtle but important difference between copying from dir1 and from dir1/*.

Moving and/or renaming is done with mv:

mv filename dir Move a file to some directory dir


Mueve todos los archivos

mv something* dir Moves all files with names matching something* to the directory dir
mv -r dir1 dir2 Move all files and subdirectories in dir1 to a new directory dir2/dir1
mv -r dir1/* dir2 Move all files and subdirectories in dir1 into the existing directory dir2
mv filename newname Rename a file or directory
mv filename dir/newname Move a file to some directory dir and rename it
directorio de destino
When moving and copying with mv and cp, the target directory must already exist.

Use mkdir and rmdir to create and remove directories:

mkdir Aug21 Make a new directory within the current directory


mkdir ~/data/Aug21 Make a new directory (Aug21 in this case) in ~/data
rmdir ~/data/Aug21 Remove a directory (Aug21 in this case) from ~/data

como precaución contra los lapsos de juicio de borrar directorios que aún contienen archivos
But note that Linux prevents you (as a precaution against lapses of judgment) from deleting directories that still contain files. This can
be a lifesaver: bit it can also be a chore to delete all files before being allowed to issue the rmdir command. However I expect that you
will eventually discover the way around this default behaviour, which will enable you to delete a directory and all its contents (including
subdirectories) with a single command.

Removing files is done with rm:

rm filename Delete a particular file from the current directory


rm dir/filename* Delete files matching the pattern filename* from the directory dir

The commands described above are just the start. You will find that each command has many, many options — and the way to learn about
the other options is to consult the 'man' pages:
Enumera todos los comandos relacionados de alguna manera con el PDF
man -k PDF Lists all commands connected in any way to PDF → apropos PDF

man ls Tells you everything about ls


man rm Tells you everything about rm
etc etc
opción
↓ comando opción es una manera de averiguar lo que está disponible
With hundreds of commands available man might seem of little use to neophytes. The man -k keyword option is one way to find out what is
available; others are the thematic lists in Some common commands, and the excellent Linux in a Nutshell. → Linux en resumen/en esencia
También es útil conocer sobre redirección Salida es comúnmente listado en la terminal , pero puede ser redirigida a un archivo con el comando ' > '
It is also useful to know about redirection. Output is commonly listed on the terminal, but can be redirected to a file with the '>' command. Thus

ls -1 ~/data > names.txt

Así almacena la salida como un archivo nombrado names.txt, sobrescribir el archivo preexistente de este nombre En su caso (Una variación de este comando de redirección de la salida es

stores the output as a file named names.txt, overwriting the pre-existing file of this name, if any.que(Aobtiene
variation of this output redirection command
el cual añade la salida a un archivo existente , más bien sobrescribir El opuesto es la entrada de un archivo en lugar del teclado
is '>>', which appends the output to an existing file, rather than overwriting.) The opposite is '<', which gets input from a file rather than the
keyboard, e.g.

mail -s 'Hi' < letter.txt → Todo lo que tenga el archivo se mostará

• Programa puede ser ejecutado en el ' de fondo ' por añadiendo un '&' en la línea de comandos
Programs can be run in the 'background' by appending an ampersand ('&') to the command line. Thus

gv doc.ps & # El programa se ejecuta de fondo

Así lanza ghostview y lo pone en segundo plano Que significa 'de fondo' y por qué desearía hacer esto ? Sin el &
launches ghostview and puts it in thelo background. What does 'background' mean, and why would you want to do lanzar
que significa que no hay nuevos comandos puede ser introducidos por la línea de comandos
this?elWithout the ampersand
programa en el fondo
el programa ejecuta en el primer plano
the program runs in the foreground, which means that no new commands can be entered on the command line. Launching the program in the
permite nuevos comandos ser introducidos en la línea de comando
background allows new commands to be entered on the command line. The program operates identically in both cases.
Hay miles de comandos documentados en las páginas man
There are thousands of commands documented in the man pages. If you want to see for yourself, type
Argumentos Extendidos - eXtended ARGuments

find /usr/share -name 'man' -type d | xargs ls -lR → Lista todos los comandos del directorio usr/share

que también le da una idea de la manera sofisticada en que todos esos comandos se pueden utilizar es usado ver para todos directorios
which also gives you a taste of the sophisticated way in which all those commands can be used. In this example, find is used to look for all
nombrados 'man' en el directorio incluyendo todos los subdirectorios que producen una lista de directorios que contiene pagina 'man'
directories named 'man' in the directory /usr/share, including all its subdirectories. That produces a list of directories that contain man pages.
El listar no esta imprimido ; en su lugar ello esta 'pipetado' al comando xargs el cual construye comandos como 'ls -lR dirname' cada uno de los cuales genera un listado
The list is not printed: instead it is 'piped' to the xargs command, which constructs commands like ls -lR dirname, each of which generates a
recursivo de todos los archivos en el directorio man y sus subdirectorios el resultado es que el comando compuesto sobre localiza y lista todas las paginas de manual
recursive directory listing of all files in the man directory, and its subdirectories. The upshot is that the compound command above locates and
rama del árbol de directorios
por muy dispersos que estén en el
lists all man pages, however scattered they are in the /usr/share branch of the directory tree. You can augment the above command slightly:

find /usr/share -name 'man' -type d | xargs ls -lR | wc -l → 4999 - Muestra por pantalla el total de palabras del directorio de los manuales

• Encuentra dentro del direcotrio share el elemento man de tipo directorio ↓
Se utiliza para usar como parametros la salida del comando anterior para pasarselo al siguiente comando

Pasamos el resultado como argumento al comando ls para que lo liste y le pasa la salida al comando 'wc' para que diga la cantidad de palabras y demas tiene
Puede aumentar ligeramente el comando anterior para obtener un recuento aproximado del número de páginas man
Pero incluso esto es un ejemplo bastante elemental del poder de los comandos de Unix/Linux.
to get an approximate count of the number of man pages. But even this is a rather elementary example of the power of Unix/Linux commands.

Algunos comandos comunes


Some common commands
Aquí están algunos comandos útiles Ellos son una timida fracción de la línea de comandos disponible , pero pero dar una muestra de lo que se puede lograr
Here are some more useful commands. They are a tiny fraction of the vea
Muchos de los comandos de abajo están las utilidades principales de Linux
command-line programs available, but give a taste of what can be
las paginas 'man' para más información sobre su proposito y mas sobre sus opciones
accomplished. Most of the commands below
donde yace su verdadero poder
are core Linux utilities. See the 'man' pages for
También se enumeran a continuación son varias aplicaciones grandes
more about their purpose, and more about their
que tienden a tener instrucciones incorporadas
options — wherein lies their real power. Also listed below are several large applications, which tend to have built-in instructions.
Si eres un recién llegado a Linux puede que no entiendas el sentido de los comandos que se enumeran a continuación o dudar de su valor Todo lo que puedo decir es que los he usado todos
If you are a newcomer to Linux you may not understand the point of the commands listed below, or doubt their value. All I can say is that I
y considerar cada uno de ellos útil o incluso inestimable.
have used them all, and consider each one useful or even invaluable.
Gestión de archivos
File management
Convertir un archivo de texto en PostScript imprimirlo
a2ps Convert a text file to PostScript, and (by default) print it
Concatenar archivos de texto o simplemente mostrar archivos de texto
cat Concatenate text files — or simply display text files
Cambio el mismo directorio
cd Change to some other directory
Cambio el grupo el cual pertenece un archivo
chgrp Change the group to which a file belongs
Cambio modo acceso para hacer que un archivo sea invisible para los demás
chmod Change access modes, e.g. chmod go-rwx file1 to make a file invisible to others
chown Change the owner of a file
cp Copy files
Volcar un archivo mostrando las versiones hexadecimal y ASCII
hd Dump a file, showing both hex and ASCII versions
Mostrar las primeras líneas de un archivo
head Display the first few lines of a file
Mostrar un archivo , pagina por pagina
less Display a file, page by page
crear un enlace (alias) para un archivo
ln Create an alias ('link') for a file, e.g. ln -s current_name new_name
Listar archivos contenidos en un directorio
ls List files contained in a directory
Crear un directorio
mkdir Create a directory
Mover or renombrar archivos o directorios
mv Move or rename files or directories
Imprimir el presente directorio de trabajo
pwd Print the present working directory (where am I?)
eliminar archivos
rm Remove files
eliminar un directorio
rmdir Remove a directory
Mostrar las últimas líneas de un archivo Los parámetros son:
tail Display the last few lines of a file
Contador de palabras - también la linea y contador de caracteres
OPCION: permite indicar a scp parámetros como cifrado, configuración ssh, puerto ssh, límite, copia recursiva y más
wc Word count — also the line and character count Usuario 1: archivo de origen.
Usuario 2: archivo de destino.
-P: indica el puerto ssh del host remoto.
-p: permite conservar la modificación de archivos y los tiempos de acceso al mismo.
Communication -q: con esta opción podemos suprimir el medidor de progreso y los mensajes sin error generados.
-C: se obliga a scp a comprimir los datos durante el envío al equipo de destino.
-r: permite indicar a scp que copie directorios de forma recursiva los datos.
Tranferir archivos
scp File transfer → OpenSSH secure file copy Copiar archivos a, desde o entre diferentes hosts en ambientes Linux. El comando scp (secure copy) hace uso de ssh para las tares de
transferencia de datos y cuenta con la autenticación y seguridad de ssh.
Tranferir archivos
• El protocolo SFTP permite una serie de operaciones sobre archivos remotos.
sftp File transfer → SSH File Transfer Protocol • SFTP intenta ser más independiente de la plataforma que SCP, por ejemplo,
• SCP soporta expansión de comodines especificados por el cliente hasta el servidor, mientras que el diseño SFTP evita este problema.
Aunque SCP se aplica con más frecuencia en plataformas Unix, existen servidores SFTP en la mayoría de las plataformas.
ssh For terminal-like sessions on remote hosts ssh - Secure SHell :Protocolo y programa
* Función acceso remoto al servidor por medio de un canal seguro en el que la información está cifrada.
* La conexión a otros dispositivos
* Permite copiar datos de forma segura (tanto archivos sueltos como simular sesiones FTP cifradas)
* Gestionar claves RSA para no escribir contraseñas al conectar a los dispositivos y pasar los datos de cualquier otra aplicación por un canal seguro tunelizado mediante SSH
File comparisons * Puede redirigir el tráfico del (Sistema de Ventanas X) para poder ejecutar programas gráficos remotamente
* El puerto **TCP** asignado es el **22**.

Compara 2 archivos usualmente archivos binarios , byte por byte


cmp Compare two files (usually binary files), byte by byte
Compara 2 archivos usualmente archivos ASCII , línea por línea
diff Compare two files (usually ASCII files), line by line
kompare Compare two files graphically

Graphics
programa
display For image viewing and manipulation — moderately elaborate
programa
gimp For image manipulation — very elaborate
ksnapshot For screen capture
xfig For creating line drawings
xv For image viewing and manipulation — not too elaborate
Printing

lpq Show contents of printer queue


lpr Send file to printer
lprm Remove print job from queue

Searching
Buscar páginas man para un tema determinado
apropos Search man pages for given topic
Búsqueda de nombres de archivos en el árbol de directorios
find Search directory tree for specific filenames
Buscar palabras específicas en los archivos de texto
grep Search text files for specific words
Buscar archivos basados en nombres parciales
locate Find files based on partial names
Extraer todos los textos de un archivo
strings Extract all text from a file

Bundling of files Agrupación de archivos

bzip2 Compress a file, producing a .bz2 file


bunzip2 Uncompress a .bz2 file
compress Compress a file, producing a .Z file
gunzip Uncompress either a .gz or .Z file
gzip Compress file, producing a .gz file
tar Bundle many files into one • Bundle : paquete , fardo , manojo , haz , montón

uncompress Uncompress a .Z file

Tratamiento de textos
Text processing
Escaneo de patrones y lenguaje de procesamiento de texto
awk Non-interactive editor (line-orientated) Puede indicar a AWK que imprima solo determinadas columnas del campo de entrada. El siguiente ejemplo demuestra esto:
eliminar secciones de cada línea de archivos
cut Select particular columns from a text file
Convertidor de archivos de texto de formato DOS/Mac a Unix y viceversa
dos2unix Deal with the DOS vs Unix newline difference
emacs Elaborate text editor
Editor de texto amigable
nedit Friendly text editor
Editor no interactivo editor de secuencias
sed Non-interactive editor (stream-oriented)
Ordenar o funsionar archivos
sort Sort or merge files
Convertir (redifinir o eliminar) caracteres
tr Translate (redefine or delete) characters, e.g. tr -d ',' < fil > fil2
unix2dos Deal with the DOS vs Unix newline difference
vi Classic text editor

Word processing

kword Similar to Word™


ooffice Similar to Word™
latex Utterly unlike Word™
dvips Turns LaTeX output into PostScript
dvipdf Turns LaTeX output into PDF
ps2pdf Turns PostScript into PDF
gv For viewing PostScript and PDF documents
xpdf For viewing PDF documents
acroread For viewing PDF documents

Status
Mostrar la capacidad y el uso de cada partición
df Show the capacity and usage of each partition
Mostrar el tamaño de todos los subdirectorios
du Show the size of all subdirectories
Mostrar todas las variables de entorno
env Show all environment variables Mata el proceso
Terminar un programa en ejecución ↓
kill Terminate a running program, e.g. kill -9 10283
Alterar la prioridad de un programa en ejecución
renice Alter the priority of a running program, e.g. renice -n 10 12872
Mostrar todos los programas en ejecución
ps Show all running programs, e.g. ps -ef
Mostrar el uso del disco y la cuota
quota Show your disk usage and quota
Mostrar los programas activos
top Show active programs

Miscellaneous

clear Clear the terminal window


señalar
finger Find out about a user, e.g. finger paul
descargar ispell Spell checker
man Display a man page
passwd Alter your password cambia la contraseña del usuario y grupo
source Run a C shell script, e.g. source ~/.cshrc
¿Quién está conectado
w Who is logged on
Ver ruta de programas
which Show the full path of a program
xargs Organizes multiple command line arguments
Administrar recursos de un servidor
xrdb Manage your X11 resources, e.g. xrdb .Xdefaults

Note: Linux is astonishingly diverse in its manifestations, and is evolving rapidly. Consequently you may find that as many as 5 to 10% of the
above commands are unavailable on your system. The common commands are quite stable, however.
Some examples
Algunos de los comandos en Algunos comandos comunes son tan comunes y útiles que merecen algunos comentarios más.
Some of the commands in Some common commands are so common and useful that they deserve a few more comments.

gzip and gunzip

These are used for compressing and uncompressing files. Typically you will have a file, for example Study0223.tar, that you want to compress
before FTP'ing it to some other site. You just need to enter

gzip Study0223.tar

and the original file will be replaced by one named Study0223.tar.gz. Conversely, if you receive a file with the tell-tale extension .gz then
entering

gunzip Study0223.tar.gz

will expand the file to one named Study0223.tar. The uncompression command gunzip is especially useful since it can deal with several
compression formats: gzip, zip, compress, and pack. The detection of the input format is automatic.

tar
se utiliza para agrupar un grupo de archivos y escribirlo en otro archivo en lugar de grabarlo
The name tar comes from Tape ARchive, but is more commonly used to bundle a group of files and write it to another file, rather than to a
tape. A simple example would be:
Crear un nuevo archivo con los elementos creados
tar cvf tarfile.tar file1.eeg file2.eeg ... → Crear un archivo.tar con los demás archivos creados
Especifica el nombre del archivo de almacenamiento

Esto toma cualquier número de archivos especificado explícitamente o utilizando caracteres comodín y los agrupa en un archivo de salida
This takes any number of files file1.eeg file2.eeg ..., specified explicitly or using wildcard characters ('*', '?' etc), and bundles them into an
para crear un archivo la salida a un archivo con el nombre inmediatamente seguido
Las opciones son para hacerlo verbosamente
output file tarfile.tar. The options are: c to create an archive, v to do so verbosely, and f to output to a file with the immediately following
pero puede ser tranquilizador
name. (The v is optional, but can be reassuring.)
Probablemente es más común y más potente para especificar un directorio en lugar de una lista de archivos de entrada
It is probably more common (and more powerful) to specify a directory instead of a list of input files, as in:
Crear un nuevo archivo con los elementos creados

tar cvf /media/usb/backup.chris.jan.tar /suphys/chris → COPIA TODO EL DIRECTORIO 'chrish' y lo almacena en el archivo 'chris'
↓ Archivo que se crea al comprimir el directorio - Salida Copia todo el Directorio 'chris' y lo comprime - Entrada
Especifica el nombre del archivo de almacenamiento
Una advertencia: es a la vez ilógico y malo para 'tar'
which is what I might do to back up my home directory, including all subdirectories. A warning though: it is both illogical and bad to tar a
que es lo que podría hacer para respaldar mi directorio personal, incluidos todos los subdirectorios
un directorio y escribir el archivo de salida en ese mismo directorio
directory and write the output file to that same directory!
Si recibe un archivo tar, por ejemplo somefile.tar, le sugiero que primero mire su contenido
If you receive a tar file, say somefile.tar, then I suggest you first look at its contents by
Muestra el contenido de salida

tar tf somefile.tar → Muestra el contenido de archivo comprimido
especifica el nombre del archivo de almacenamiento

Esto producirá una lista de los archivos adjuntos incluyendo cualquier subdirectorio. Cuando descomprimes el archivo los archivos de la lista incluyendo los subdirectorios
This will produce a list of the enclosed files, including any subdirectories. When you
y esto podría no ser lo que quieres
untar the file, the listed files — including subdirectories
Es aconsejable utilizar la opción t para anticiparse a lo que ocurrirá exactamente
puede crearse en el directorio actual
— can be created in the current directory, and this might not be what you want. It is advisable to use the t option to anticipate exactly what
al extraer el contenido del archivo tar Tal vez deba mover el archivo tar a un subdirectorio con el nombre adecuado antes de extraer su contenido
will happen when you extract the contents of the tar file. Perhaps you should move the tar file into a suitably-named subdirectory before
Lo que no quieres hacer es extraer muchos archivos y luego encontrar que se mezclan irremediablemente con archivos preexistentes
extracting its contents. What you don't want to do is extract lots of files, and then find that they are hopelessly mixed up with pre-existing
filesÂ…
Cuando esté seguro de que el archivo tar está en una ubicación adecuada se puede extraer todo con
When you are satisfied that the tar file is in an appropriate location, you can extract everything with
Extraer el archivo de almacenamiento

tar xvf somefile.tar
Especifica el fichero de almacenamiento

Dónde 'x' significa extraer tiene el usual significado En ocasiones, los usuarios desearán extraer uno o varios archivos específicos
where x means extract, and v and f have the usual meanings. Users will occasionally wish to extract a specific file or files: that is easily
que se consigue fácilmente añadiendo los nombres de los archivos necesarios
achieved by appending the names of the required files, as in

tar xvf somefile.tar go-nogo/10038259/slice5.dcm

El archivo solicitado se creará en un subdirectorio bajo el directorio actual


The requested file 'slice5.dcm' will then be created in a subdirectory 'go-nogo/10038259/' under the current directory.

find
Mientras el comando puede ser adecuado la mayor parte del tiempo para localizar archivos el comando es mucho más potente. El uso
While the command locate may be adequate much of the time for tracking down files, the command find is far more powerful. The basic
y todos los subdirectorios
básico es Busca en el directorio
usage is find directory criterion. It searches in directory directory, and all subdirectories, for anything matching criterion. Thus you could
enter

find ~/docs -name thesis.doc

buscar 'tesis.doc' entre sus documentos personales


to look for thesis.doc among your personal documents, or

find ~ -name 'note*'

para encontrar archivos con nombres que coincidan con Tenga en cuenta que las comillas son esenciales cuando se utilizan caracteres comodín con
to find files with names matching note*. (Note that the quotes are essential when using wildcard characters with find.)
Puede buscar nombres de directorios concretos, así como nombres de archivos Si quiere ser específico puede ampliar el criterio añadiendo
You can search for particular directory names, as well as file names. If you wish to be specific, you could expand the criterion by appending
-type d or -type f.
Los criterios pueden ir mucho más allá de los casos sencillos anteriores
The criteria can go far beyond the simple cases above. Here are a few more examples:

find ~ -atime -4 All files under ~ accessed in last 4 days


find ~ -mtime -4 All files under ~ modified in last 4 days
find / -user chris List all files owned by chris
find ~ -name 'core.*' -exec rm {} \; Delete all core dumps
El comando 'find' es incluso más poderoso en combinación con otros usuarios
Lo mismo, Un ejemplo muy común es este ; desea identificar un subconjunto de archivos
pero excluyendo dos subdirectorios
The find command is even more powerful in combination with others. A very common example is this: you want to identify a subset of files
(*.tex) within some directory (~/docs) and all subdirectories; and to search within this subset of files for a particular string of characters
('needle'). The way to do this is:

find ~/docs -name '*.tex' | xargs grep -n 'needle'

La salida muestra , para cada coincidencia , el archivo , el número de línea y el línea así misma
The output shows, for each match, the file, line number and the line itself.
El siguiente muestra progresiva elaboración de un ' find ' que en la ultima instancia realiza un archivo selectivo de todos los archivos recientemente modificados.
The following shows progressive elaboration of a find, which ultimately performs a selective archive of all recently modified files.

Todos archivos bajo y que ha sido creado , modificado o tiene sus estatus cambiado en los últimos 75 días
1 argumento 2 argumento
find ./progs ./tex -ctime -75 -type f
opción argumento argumento
All files under ./progs and ./tex that have been created, modified, or had their status
comando 1 ruta del archivo 2 ruta del archivo
tiempo modificación
tiempo tipo de archivo changed in the last 75 days

find ./progs ./tex -ctime -75 -type f \ idem , pero excluye 2 subdirectorios
-o -path ./progs/corejsf -prune \ Ditto, but exclude two subdirectories
-o -path ./progs/jeda/build -prune

find ./progs ./tex -ctime -75 -type f \


-o -path ./progs/corejsf -prune \ idem , pero adicionalmente montón los archivos como
-o -path ./progs/jeda/build -prune \ Ditto, but additionally bundle the files as backup.tar
| xargs tar cvf backup.tar

make
Es muy común usar la utilidad 'make' cuando compilas programas aunque la marca puede utilizarse para realizar todo tipo de operaciones. Esta utilidad mira para
It is very common to use the make utility when compiling programs, although make can be used for doing all sorts of operations. This utility looks
un archivo, convencionalmente nombrado
for a file, conventionally named Makefile, and performs any one of several sets of commands.
y realiza cualquiera de varios conjuntos de comandos
Un ejemplo ' Makefile' es el siguiente
An example Makefile is as follows:
Contenido del archivo 'Makefile'
PROG =eegfit
CC =gcc
Para la creación de perfiles, añada -pg, para lo cual -g3 es un requisito previo
# For profiling support add -pg, for which -g3 is a prerequisite
CFLAGS_G = -Wall
CFLAGS_D = -g3 -ggdb
CFLAGS_R = -O
CFLAGS =$(CFLAGS_G) $(CFLAGS_D)
Para la creación de perfiles, añada -pg
# For profiling support add -pg
LFLAGS_G = -lX11 -lm -lncurses -L/usr/X11R6/lib
LFLAGS_D =
LFLAGS_R =
LFLAGS =$(LFLAGS_G) $(LFLAGS_D)

SOURCES = eegfit.c spectfit.c xlib.c gammq.c \


gser.c gcf.c gammln.c ran1.c gasdev.c
OBJECTS = eegfit.o spectfit.o xlib.o gammq.o \
gser.o gcf.o gammln.o ran1.o gasdev.o

%.o: %.c
$(CC) $(CFLAGS) -c $<

eegfit: $(OBJECTS)
$(CC) -o $@ $(OBJECTS) $(LFLAGS)

clean:
rm -f *.o $(PROG)

all:
$(CC) $(CFLAGS) -c $(SOURCES)
$(MAKE)

tar:
tar -cvf eegfit.tar $(SOURCES) *.h makefile

# Dependencies
eegfit.o: parameter.h
spectfit.o: parameter.h xlib.h
xlib.o: xlib.h

Este ejemplo ' makefile' especifica todo los archivos involucrados en un programa , 'eegfit' y todas las operaciones necesarias para alcanzar determinados fines compilación
This example makefile specifies all the files involved in a program, eegfit, and all the operations required to achieve certain ends: compilation,
starting afresh, and creating a tar archive. Having created this makefile, it is then just a matter of typing one of the following:
empezando de nuevo y crear un archivo tar Habiendo creado este makefile entonces sólo es cuestión de escribir uno de los siguientes datos
make eegfitCompile the application
make Ditto
make clean Delete the object files and the executable
make tar Bundle all source files into eegfit.tar

entorno
Environment
La clave para una ejecución conveniente del programa es entender su Se trata de una variable de "entorno". se puede examinar escribiendo
The key to convenient program execution is understanding yourcada $PATH. This is an 'environment' variable: it can be examined by typing echo
vez que intente ejecutar un programa
y lista todos directorios que son buscados automáticamente Si un programa con el nombre que usted especifica se encuentra en
$PATH, and it lists all directories that are searched automatically whenever you try to run a program. If a program with the name you specify is
cualquiera de los directorios listados en entonces se ejecuta de lo contrario, recibirá un mensaje
found in any of the directories listed in $PATH, then it is run — otherwise you get a message Command not found.
Como ejemplo de visualización del
As an example of displaying the $PATH:

echo $PATH
/bin:/usr/bin:/usr/bin/X11:/usr/local/bin:/usr/X11R6/bin:.

El presente de '/bin' es la razón puedes escribir 'vi' en lugar tener escribir todo , explicita ruta Cada vez que deseas editar un archivo
The presence of '/bin' is the reason you can type vi instead of having to type the full, explicit path /bin/vi, whenever you want to edit a file.
For the same reason the '.' at the end means that programs in your current directory can be run without any directory prefix.
Para la misma razón el al final significa que los programas en su directorio actual pueden ser ejecutados sin ningún prefijo de directorio
Unix C shell Este es un archivo de configuración para su intérprete de comandos o 'shell'
You are free to alter the $PATH variable, and the best way to do so is in your .cshrc file. This is ayconfiguration
mucho más.
file for your command interpreter
y puede ser visto por Por lo general, verá en él referencias a Si quieres anteponer algún directorio a tu
or 'shell', and can be viewed by less ~/.cshrc. You will generally see in it references to setenv and much else besides. If you want to prepend
(su directorio personal de programas
some directory to your $PATH (your personal program directory ~/bin, say) then type either of

setenv PATH ~/bin:$PATH


set path=(~/bin $path)

(ambos hacen lo mismo y a partir de entonces podrás ejecutar tu programa (digamos) simplemente escribiendo independientemente de su directorio actual
(both do the same thing), and from then on you will be able to run your program ~/bin/model (say) just by typing model, irrespective of your
current directory. Solo esta disponible en :
En realidad, es mejor colocar la línea anterior en su Unix C shell de lo contrario, el cambio se limita a la ventana de la terminal en la que se ha escrito.
Actually it is better to place the above line in your .cshrc file — otherwise the change is limited to the terminal window in which you typed it.
le dará una lista completa de variables de entorno los que especificó en su más las que el sistema operativo establece automáticamente
Typing printenv will give you a full list ofdiscutido
environment variables: those you specified in your .cshrc file, plus those that the operating system
anteriormente la variable de entorno
Verás que especificó su impresora preferida
sets automatically. You will see $PATH, discussed above, the environment variable $PRINTER, which specified your preferred printer, $DISPLAY,
which says where graphics are to appear, and much else.
que dice dónde deben aparecer los gráficos, y mucho más.
que definen los atajos de teclado personales Por ejemplo, si usted escribe habitualmente
Note the alias commands in .cshrc, which define personal keyboard shortcuts. For example if you routinely type

ssh joe.physics.usyd.edu.au

to access the computer 'joe' then you can add

alias ssh-joe 'ssh joe.physics.usyd.edu.au'

to your .cshrc and then access joe just by typing ssh-joe.

Shell programming
Once you are comfortable with Unix/Linux commands, you can considering even more interesting operations.
separando una colección de archivos numerados en serie con nombres como
Consider the hypothetical problem of separating a collection of serially-numbered files with names like mr2366.dcm, mr2367.dcm, mr2368.dcm,
Quiere copiar sólo los trozos impares en un directorio vecino llamado al tiempo que se cambia el nombre de los archivos copiados a
Â…. You want to copy just the odd-numbered slices to a neighbouring directory named Odd, while
Si sólo hubiera que mover tres o cuatro archivos
also renaming the copied files to
entonces podría emitir una serie de
mrOdd2367.dcm, mrOdd2369.dcm, Â…. If there were just three or four files needing to be moved, then you could issue a series of explicit mv
Pero para cualquier otra cosa deberías considerar usar el poder de programación del shell
commands, one per file. But for any more you should consider using the programming power of the shell.
En el caso hipotético anterior, la solución sería introducir las siguientes tres líneas en el prompt del shell
In the above hypothetical case, the solution would be to enter the following three lines at the shell prompt:

foreach f ( *[13579].dcm )
mv $f ../Odd/`echo $f | sed 's/mr/mrOdd/'`
end

La primera línea busca todas las trozos impares y para cada uno crea un comando 'mv' definido por la segunda línea una serie de comandos
The first line looks for all odd-numbered slices, and for each creates a mv command defined by the second line. As a result, a series of
como los que podría haber escrito manualmente
commands, like those that you could have typed manually, is executed automatically:

mv mr2367.dcm ../Odd/mrOdd2367.dcm
mv mr2369.dcm ../Odd/mrOdd2369.dcm
:

La programación Shell es sin duda un tema avanzado Sin embargo, a menudo es la solución perfecta para un problema.
Shell programming is undoubtedly an advanced topic. However it is often the perfect solution to a problem. Long or frequently-used sets of
commands can be bundled into a shell script, and the script can then be run as a single command. (You will need to chmod it as well, to make it
executable.) In the above example, the 3-line script might be named extract_odd, and run simply by typing this name. It doesn't get much
easier than that.
Scripting can be about moving files and manipulating filenames. It can also be about modifying the contents of files. sort, cut and join can be
used to rearrange tabular material very simply. The utilities sed and gawk provide more powerful programmatic methods for modifying, collating,
and extracting values in text files. For example, if a file contains columns of numbers, and you want to see just the first column and the ratio of
the next two, then

gawk '{if(NF>=3) print $1,$2/$3}' dat.txt

will do the job.

Finally, the code below is a realistic example of a shell script, whose goal should be obvious. To maximize its utility the script (named t2ps) is
placed in ~/bin, which should be made part of your $PATH.

#!/bin/tcsh
if ($#argv == 0) then
echo -n "File(s): "
set filelist = ($<)
else
set filelist = ($argv[*])
endif

# Strip extensions, if present


set filelist = ($filelist:gr)

# Process each file, checking first that each exists


foreach filename ( $filelist )
if ( -e $filename.tex && -f $filename.tex ) then
latex $filename.tex && dvips $filename -o && rm $filename.{aux,dvi,log}
else
echo "t2ps: input file $filename.tex not found"
endif
end

Shell programming is a big topic. Reading man tcsh (or man bash) is a start, but a difficult one. I recommend books like Linux in a Nutshell and
Redhat Linux Toolbox, which concisely cover all topics and provide brief examples. Also I like and recommend the many freely-available
reference cards: see, for example, the collection at www.cheat-sheets.org.

Validate HTML CSS Last changed 2011-04-05 Chris Rennie

You might also like