Tabla de contenido
Comandos básicos (relacionados con directorios de archivos)
prefacio
Linux es un sistema operativo de código abierto y su estructura de directorios es muy importante porque es la base para utilizar el sistema Linux. Este artículo presentará algunos comandos comunes para operar archivos y directorios en el sistema Linux, algunos de los cuales también tienen comandos correspondientes en Dos (refiriéndose a funciones similares).
Otra diferencia es que los comandos en el sistema Linux distinguen entre mayúsculas y minúsculas, generalmente todos en minúsculas; los comandos en el sistema Dos no distinguen entre mayúsculas y minúsculas y las mayúsculas y minúsculas del nombre del comando son las mismas, como cd CD cD Cd es lo mismo un pedido.
Comandos básicos (relacionados con directorios de archivos)
comando cd
cd: cambia el directorio de trabajo actual. Se pueden utilizar rutas absolutas o relativas.
El comando para ingresar al directorio raíz es: cd /, y el comando para ingresar al directorio de inicio del usuario es: cd ~.
Entre ellos, "/" y "~" representan el directorio raíz y el directorio de inicio del usuario actual, respectivamente.
Cambio del modo de ruta absoluta : Cambio del modo cd /home/user/documents
de ruta relativacd ../user/documents
: donde, la ruta absoluta se refiere a la ruta que comienza desde el directorio raíz; la ruta relativa se refiere a la ruta que comienza desde el directorio actual.
【Ayuda en inglés】
hann@HannYang:~$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed: resolve symbolic
links in DIR after processing instances of `..'
-P use the physical directory structure without following
symbolic links: resolve symbolic links in DIR before
processing instances of `..'
-e if the -P option is supplied, and the current working
directory cannot be determined successfully, exit with
a non-zero status
-@ on systems that support it, present a file with extended
attributes as a directory containing the file attributes
The default is to follow symbolic links, as if `-L' were specified.
`..' is processed by removing the immediately previous pathname component
back to a slash or the beginning of DIR.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
【Comando Dos correspondiente】
cd Mismo nombre y misma función, formato: ruta del directorio del cd
Muestra el nombre del directorio actual o cambia el directorio actual. o chdir con el nombre largo
CHDIR [/D] [unidad:][ruta]
CHDIR [..]
CD [/D] [unidad:][ruta]
CD [..]
.. Especifica cambiar al directorio principal.
Escriba unidad de CD: para mostrar el directorio actual en la unidad especificada.
Escriba CD sin argumentos para mostrar la unidad y el directorio actuales.
Utilice el modificador /D para cambiar la unidad actual además de
cambiar el directorio actual de la unidad.
Si las extensiones de comando están habilitadas, CHDIR cambia de la siguiente manera:
La cadena del directorio actual se convertirá para usar mayúsculas y minúsculas en el nombre del disco. Entonces, CD C:\TEMP establecerá el directorio actual en C:\Temp
si el caso en el disco es así .
El comando CHDIR no trata los espacios como separadores, por lo que es posible cambiar el nombre del directorio a un
nombre de subdirectorio con espacios pero sin comillas. Por ejemplo:
cd \winnt\profiles\nombre de usuario\programas\menú de inicio
Igual que:
cd "\winnt\profiles\nombre de usuario\programas\menú de inicio"
Con la extensión deshabilitada, debes escribir el comando anterior.
comando pwd
pwd: muestra la ruta del directorio de trabajo actual. Por ejemplo, pwd
se mostrará la ruta completa al directorio de trabajo actual.
El comando pwd se utiliza para mostrar la ruta absoluta del directorio de trabajo actual (es decir, el directorio actual). En el sistema Linux, cada usuario tiene su propio directorio de inicio. Cuando inicia sesión por primera vez en el sistema, el directorio en el que se encuentra es el directorio de inicio del usuario.
hann@HannYang:~$ contraseña
/casa/hann
【Ayuda en inglés】
hann@HannYang:~$ pwd --help
pwd: pwd [-LP]
Print the name of the current working directory.
Options:
-L print the value of $PWD if it names the current working
directory
-P print the physical directory, without any symbolic links
By default, `pwd' behaves as if `-L' were specified.
Exit Status:
Returns 0 unless an invalid option is given or the current directory
cannot be read.
【Comando Dos correspondiente】
No hay un comando pwd separado en Dos, solo use el comando CD sin parámetros:
C:\Usuarios\hann>CD
C:\Usuarios\hann
C:\Usuarios\hann>cD
C:\Usuarios\hann
C:\Usuarios\hann>Cd
C:\Usuarios\hann
C:\Usuarios\hann>cd
C:\Usuarios\hann
ls comando
ls: muestra una lista de archivos y directorios en el directorio actual o especificado.
Los parámetros del comando ls son extremadamente complicados: el valor predeterminado es la visualización en formato corto, solo el nombre del archivo y el formato detallado puede usar el parámetro -l para mostrar la lista de archivos y directorios en el directorio en formato largo, incluido el archivo. tamaño, permisos, propietario, tiempo de modificación, etc.
【Ayuda en inglés】
hann@HannYang:~$ ls --help
Usage: ls [OPTION]... [FILE]...
List information about the FILEs (the current directory by default).
Sort entries alphabetically if none of -cftuvSUX nor --sort is specified.
Mandatory arguments to long options are mandatory for short options too.
-a, --all do not ignore entries starting with .
-A, --almost-all do not list implied . and ..
--author with -l, print the author of each file
-b, --escape print C-style escapes for nongraphic characters
--block-size=SIZE with -l, scale sizes by SIZE when printing them;
e.g., '--block-size=M'; see SIZE format below
-B, --ignore-backups do not list implied entries ending with ~
-c with -lt: sort by, and show, ctime (time of last
modification of file status information);
with -l: show ctime and sort by name;
otherwise: sort by ctime, newest first
-C list entries by columns
--color[=WHEN] colorize the output; WHEN can be 'always' (default
if omitted), 'auto', or 'never'; more info below
-d, --directory list directories themselves, not their contents
-D, --dired generate output designed for Emacs' dired mode
-f do not sort, enable -aU, disable -ls --color
-F, --classify append indicator (one of */=>@|) to entries
--file-type likewise, except do not append '*'
--format=WORD across -x, commas -m, horizontal -x, long -l,
single-column -1, verbose -l, vertical -C
--full-time like -l --time-style=full-iso
-g like -l, but do not list owner
--group-directories-first
group directories before files;
can be augmented with a --sort option, but any
use of --sort=none (-U) disables grouping
-G, --no-group in a long listing, don't print group names
-h, --human-readable with -l and -s, print sizes like 1K 234M 2G etc.
--si likewise, but use powers of 1000 not 1024
-H, --dereference-command-line
follow symbolic links listed on the command line
--dereference-command-line-symlink-to-dir
follow each command line symbolic link
that points to a directory
--hide=PATTERN do not list implied entries matching shell PATTERN
(overridden by -a or -A)
--hyperlink[=WHEN] hyperlink file names; WHEN can be 'always'
(default if omitted), 'auto', or 'never'
--indicator-style=WORD append indicator with style WORD to entry names:
none (default), slash (-p),
file-type (--file-type), classify (-F)
-i, --inode print the index number of each file
-I, --ignore=PATTERN do not list implied entries matching shell PATTERN
-k, --kibibytes default to 1024-byte blocks for disk usage;
used only with -s and per directory totals
-l use a long listing format
-L, --dereference when showing file information for a symbolic
link, show information for the file the link
references rather than for the link itself
-m fill width with a comma separated list of entries
-n, --numeric-uid-gid like -l, but list numeric user and group IDs
-N, --literal print entry names without quoting
-o like -l, but do not list group information
-p, --indicator-style=slash
append / indicator to directories
-q, --hide-control-chars print ? instead of nongraphic characters
--show-control-chars show nongraphic characters as-is (the default,
unless program is 'ls' and output is a terminal)
-Q, --quote-name enclose entry names in double quotes
--quoting-style=WORD use quoting style WORD for entry names:
literal, locale, shell, shell-always,
shell-escape, shell-escape-always, c, escape
(overrides QUOTING_STYLE environment variable)
-r, --reverse reverse order while sorting
-R, --recursive list subdirectories recursively
-s, --size print the allocated size of each file, in blocks
-S sort by file size, largest first
--sort=WORD sort by WORD instead of name: none (-U), size (-S),
time (-t), version (-v), extension (-X)
--time=WORD with -l, show time as WORD instead of default
modification time: atime or access or use (-u);
ctime or status (-c); also use specified time
as sort key if --sort=time (newest first)
--time-style=TIME_STYLE time/date format with -l; see TIME_STYLE below
-t sort by modification time, newest first
-T, --tabsize=COLS assume tab stops at each COLS instead of 8
-u with -lt: sort by, and show, access time;
with -l: show access time and sort by name;
otherwise: sort by access time, newest first
-U do not sort; list entries in directory order
-v natural sort of (version) numbers within text
-w, --width=COLS set output width to COLS. 0 means no limit
-x list entries by lines instead of by columns
-X sort alphabetically by entry extension
-Z, --context print any security context of each file
-1 list one file per line. Avoid '\n' with -q or -b
--help display this help and exit
--version output version information and exit
The SIZE argument is an integer and optional unit (example: 10K is 10*1024).
Units are K,M,G,T,P,E,Z,Y (powers of 1024) or KB,MB,... (powers of 1000).
The TIME_STYLE argument can be full-iso, long-iso, iso, locale, or +FORMAT.
FORMAT is interpreted like in date(1). If FORMAT is FORMAT1<newline>FORMAT2,
then FORMAT1 applies to non-recent files and FORMAT2 to recent files.
TIME_STYLE prefixed with 'posix-' takes effect only outside the POSIX locale.
Also the TIME_STYLE environment variable sets the default style to use.
Using color to distinguish file types is disabled both by default and
with --color=never. With --color=auto, ls emits color codes only when
standard output is connected to a terminal. The LS_COLORS environment
variable can change the settings. Use the dircolors command to set it.
Exit status:
0 if OK,
1 if minor problems (e.g., cannot access subdirectory),
2 if serious trouble (e.g., cannot access command-line argument).
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report ls translation bugs to <https://translationproject.org/team/>
Full documentation at: <https://www.gnu.org/software/coreutils/ls>
or available locally via: info '(coreutils) ls invocation'
【Comando Dos correspondiente】
DIR [unidad:][ruta][nombre de archivo] [/A[[:]atributos]] [/B] [/C] [/D] [/L] [/N] [/O[[:]clasificación
] ] [/P] [/Q] [/R] [/S] [/T[[:]campo de tiempo]] [/W] [/X] [/4]
[unidad:][ruta][nombre de archivo]
especifica la unidad, directorio y/o archivo a enumerar.
/A Muestra archivos con los atributos especificados.
Atributos D Directorios R Archivos de sólo lectura
H Archivos ocultos A Archivos listos para archivar
S Archivos del sistema I Archivos de índice sin contenido
L Puntos de análisis O Archivos sin conexión
- Prefijo para "no"
/B Utilice formato vacío (sin información de encabezado ni resumen ).
/C Muestra separadores de miles en tamaños de archivos. Es el valor predeterminado. Utilice /-C para
desactivar la visualización del delimitador.
/D Igual que amplio, pero los archivos están ordenados por columna.
/L Usar minúsculas.
/N Nuevo formato de listado largo con nombres de archivos en el extremo derecho.
/O Enumera los archivos en orden de clasificación.
Orden de clasificación N por nombre (alfabético) S por tamaño (de menor a mayor)
E por extensión (alfabético) D por fecha/hora (del primero al último)
G Directorio de grupo primero: prefijo para invertir el orden
/P en cada pausa después de una pantalla de información .
/Q Muestra el propietario del archivo.
/R Muestra el flujo de datos alternativo para el archivo.
/S Muestra archivos en el directorio especificado y todos los subdirectorios.
/T Controla el tiempo mostrado o utilizado para ordenar Campos de caracteres
Período de tiempo C Hora de creación
A Hora del último acceso
W Hora de la última escritura
/W Utilice formato de lista amplia.
/X Muestra nombres cortos generados para nombres de archivos que no son 8dot3. El formato es el de /N,
con el nombre corto insertado antes del nombre largo. Si no hay un nombre corto, se muestra un espacio en blanco en su lugar
.
/4 muestra el año en cuatro dígitos
Se puede preestablecer un interruptor en la variable de entorno DIRCMD.
Los interruptores con prefijo se reemplazan anteponiéndolos con - (guión) . Por ejemplo, /-W.
comando de árbol
árbol: muestra una lista de archivos y directorios en el directorio actual en una estructura de árbol.
【Ayuda en inglés】
hann@HannYang:~$ tree --help
usage: tree [-acdfghilnpqrstuvxACDFJQNSUX] [-H baseHREF] [-T title ]
[-L level [-R]] [-P pattern] [-I pattern] [-o filename] [--version]
[--help] [--inodes] [--device] [--noreport] [--nolinks] [--dirsfirst]
[--charset charset] [--filelimit[=]#] [--si] [--timefmt[=]<f>]
[--sort[=]<name>] [--matchdirs] [--ignore-case] [--fromfile] [--]
[<directory list>]
------- Listing options -------
-a All files are listed.
-d List directories only.
-l Follow symbolic links like directories.
-f Print the full path prefix for each file.
-x Stay on current filesystem only.
-L level Descend only level directories deep.
-R Rerun tree when max dir level reached.
-P pattern List only those files that match the pattern given.
-I pattern Do not list files that match the given pattern.
--ignore-case Ignore case when pattern matching.
--matchdirs Include directory names in -P pattern matching.
--noreport Turn off file/directory count at end of tree listing.
--charset X Use charset X for terminal/HTML and indentation line output.
--filelimit # Do not descend dirs with more than # files in them.
--timefmt <f> Print and format time according to the format <f>.
-o filename Output to file instead of stdout.
------- File options -------
-q Print non-printable characters as '?'.
-N Print non-printable characters as is.
-Q Quote filenames with double quotes.
-p Print the protections for each file.
-u Displays file owner or UID number.
-g Displays file group owner or GID number.
-s Print the size in bytes of each file.
-h Print the size in a more human readable way.
--si Like -h, but use in SI units (powers of 1000).
-D Print the date of last modification or (-c) status change.
-F Appends '/', '=', '*', '@', '|' or '>' as per ls -F.
--inodes Print inode number of each file.
--device Print device ID number to which each file belongs.
------- Sorting options -------
-v Sort files alphanumerically by version.
-t Sort files by last modification time.
-c Sort files by last status change time.
-U Leave files unsorted.
-r Reverse the order of the sort.
--dirsfirst List directories before files (-U disables).
--sort X Select sort: name,version,size,mtime,ctime.
------- Graphics options -------
-i Don't print indentation lines.
-A Print ANSI lines graphic indentation lines.
-S Print with CP437 (console) graphics indentation lines.
-n Turn colorization off always (-C overrides).
-C Turn colorization on always.
------- XML/HTML/JSON options -------
-X Prints out an XML representation of the tree.
-J Prints out an JSON representation of the tree.
-H baseHREF Prints out HTML format with baseHREF as top directory.
-T string Replace the default HTML title and H1 header with string.
--nolinks Turn off hyperlinks in HTML output.
------- Input options -------
--fromfile Reads paths from files (.=stdin)
------- Miscellaneous options -------
--version Print version and exit.
--help Print usage and this help message and exit.
-- Options processing terminator.
【Comando Dos correspondiente】
Similar al árbol de funciones con el mismo nombre, los parámetros del árbol de Linux son más abundantes.
Muestra gráficamente la estructura de carpetas de una unidad o ruta.
ÁRBOL [unidad:][ruta] [/F] [/A]
/F Muestra los nombres de los archivos de cada carpeta.
/A Utilice caracteres ASCII en lugar de caracteres extendidos.
comando mkdir
mkdir: crea un nuevo directorio. Por ejemplo: mkdir new_directory
un nuevo directorio llamado new_directory
.
【Ayuda en inglés】
hann@HannYang:~$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed: resolve symbolic
links in DIR after processing instances of `..'
-P use the physical directory structure without following
symbolic links: resolve symbolic links in DIR before
processing instances of `..'
-e if the -P option is supplied, and the current working
directory cannot be determined successfully, exit with
a non-zero status
-@ on systems that support it, present a file with extended
attributes as a directory containing the file attributes
The default is to follow symbolic links, as if `-L' were specified.
`..' is processed by removing the immediately previous pathname component
back to a slash or the beginning of DIR.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
【Comando Dos correspondiente】
mkdir tiene el mismo nombre y función, o utilice el nombre corto md.
Crea un directorio.
MKDIR [unidad:] ruta
MD [unidad:] ruta
Si las extensiones de comando están habilitadas, MKDIR cambia de la siguiente manera:
MKDIR crea directorios intermedios en la ruta si es necesario. Ejemplo: Suponiendo que \a no
existe, entonces:
mkdir\a\b\c\d
y:
mkdir \a
chdir \a
mkdir b
chdir b
mkdir c
chdir c
mkdir d
mismo. Si las extensiones están deshabilitadas, debe escribir mkdir \a\b\c\d.
comando rmdir/rm
rmdir: elimina un directorio vacío. Por ejemplo: rmdir empty_directory
se eliminará un directorio vacío llamado empty_directory
.
rm: Se utiliza para eliminar archivos o directorios. Si queremos eliminar un directorio y todos sus subarchivos y subdirectorios, podemos usar el comando rm con el parámetro -r, por ejemplo: rm -r ejemplo.
【Ayuda en inglés】
hann@HannYang:~$ rmdir --help
Usage: rmdir [OPTION]... DIRECTORY...
Remove the DIRECTORY(ies), if they are empty.
--ignore-fail-on-non-empty
ignore each failure that is solely because a directory
is non-empty
-p, --parents remove DIRECTORY and its ancestors; e.g., 'rmdir -p a/b/c' is
similar to 'rmdir a/b/c a/b a'
-v, --verbose output a diagnostic for every directory processed
--help display this help and exit
--version output version information and exit
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report rmdir translation bugs to <https://translationproject.org/team/>
Full documentation at: <https://www.gnu.org/software/coreutils/rmdir>
or available locally via: info '(coreutils) rmdir invocation'
hann@HannYang:~$ rm --help
Usage: rm [OPTION]... [FILE]...
Remove (unlink) the FILE(s).
-f, --force ignore nonexistent files and arguments, never prompt
-i prompt before every removal
-I prompt once before removing more than three files, or
when removing recursively; less intrusive than -i,
while still giving protection against most mistakes
--interactive[=WHEN] prompt according to WHEN: never, once (-I), or
always (-i); without WHEN, prompt always
--one-file-system when removing a hierarchy recursively, skip any
directory that is on a file system different from
that of the corresponding command line argument
--no-preserve-root do not treat '/' specially
--preserve-root[=all] do not remove '/' (default);
with 'all', reject any command line argument
on a separate device from its parent
-r, -R, --recursive remove directories and their contents recursively
-d, --dir remove empty directories
-v, --verbose explain what is being done
--help display this help and exit
--version output version information and exit
By default, rm does not remove directories. Use the --recursive (-r or -R)
option to remove each listed directory, too, along with all of its contents.
To remove a file whose name starts with a '-', for example '-foo',
use one of these commands:
rm -- -foo
rm ./-foo
Note that if you use rm to remove a file, it might be possible to recover
some of its contents, given sufficient expertise and/or time. For greater
assurance that the contents are truly unrecoverable, consider using shred.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report rm translation bugs to <https://translationproject.org/team/>
Full documentation at: <https://www.gnu.org/software/coreutils/rm>
or available locally via: info '(coreutils) rm invocation'
【Comando Dos correspondiente】
rmdir y rd son el mismo comando en Dos, pero rmdir y rm son dos comandos diferentes en Linux.
Eliminar un directorio.
RMDIR [/S] [/Q] [unidad:]ruta
RD [/S] [/Q] [unidad:]ruta
/S Elimina todos los subdirectorios y
archivos del directorio especificado además del directorio mismo. Se utiliza para eliminar un árbol de directorios.
/Q modo silencioso, con /S elimina el árbol de directorios sin pedir confirmación
comando cp
cp: copia un archivo o directorio.
cp: copia un archivo o directorio. Por ejemplo, cp file1 file2
copie file1
a file2
. Para copiar un directorio y su contenido, necesita usar -r
opciones como cp -r dir1 dir2
.
El comando cp se utiliza para copiar archivos o directorios. Por ejemplo, podemos usar el comando cp para copiar un directorio llamado "ejemplo" al directorio actual, el comando es: cp -r ejemplo.
【Ayuda en inglés】
hann@HannYang:~$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed: resolve symbolic
links in DIR after processing instances of `..'
-P use the physical directory structure without following
symbolic links: resolve symbolic links in DIR before
processing instances of `..'
-e if the -P option is supplied, and the current working
directory cannot be determined successfully, exit with
a non-zero status
-@ on systems that support it, present a file with extended
attributes as a directory containing the file attributes
The default is to follow symbolic links, as if `-L' were specified.
`..' is processed by removing the immediately previous pathname component
back to a slash or the beginning of DIR.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
【Comando Dos correspondiente】
La función principal de copiar es la misma y se llama cp para abreviar en Linux.
Copie uno o más archivos a otra ubicación.
COPIAR [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] fuente [/A | /B]
[+ fuente [/A | /B] [+ ...]] [destino [/A | /B]]
fuente especifica el archivo a copiar.
/A Indica un archivo de texto ASCII.
/B significa un archivo binario.
/D Permite descifrar el archivo de destino que se va a crear.
destino Especifica el directorio y/o el nombre del archivo para el nuevo archivo.
/V Verifica que los archivos nuevos se escribieron correctamente. /N Utilice nombres de archivo cortos cuando sea posible
al copiar archivos con nombres que no sean 8dot3 . /Y No utilice un mensaje para confirmar si se sobrescriben los archivos de objetos existentes . /-Y Utilice un mensaje para confirmar si se va a sobrescribir un archivo objeto existente. /Z Copia archivos en red en modo reiniciable. /L Si el origen es un enlace simbólico, copie el enlace al destino en lugar del archivo real al que apunta el enlace de origen.
El modificador de línea de comando /Y se puede preestablecer en la variable de entorno COPYCMD.
Esto puede anularse con /-Y en la línea de comando. A menos que el comando COPIAR
se ejecute en un script por lotes, el valor predeterminado debe ser Preguntar
al sobrescribir.
Para agregar archivos, especifique un archivo para el destino y
varios archivos para el origen (en formato comodín o archivo1+archivo2+archivo3).
comando táctil
toque: Crear un nuevo archivo vacío o actualizar los tiempos de acceso y modificación de un archivo existente. Por ejemplo, se creará touch file1
un nuevo archivo con nombre, o se actualizarán los tiempos de acceso y modificación .file1
touch file1
file1
【Ayuda en inglés】
hann@HannYang:~$ touch --help
Usage: touch [OPTION]... FILE...
Update the access and modification times of each FILE to the current time.
A FILE argument that does not exist is created empty, unless -c or -h
is supplied.
A FILE argument string of - is handled specially and causes touch to
change the times of the file associated with standard output.
Mandatory arguments to long options are mandatory for short options too.
-a change only the access time
-c, --no-create do not create any files
-d, --date=STRING parse STRING and use it instead of current time
-f (ignored)
-h, --no-dereference affect each symbolic link instead of any referenced
file (useful only on systems that can change the
timestamps of a symlink)
-m change only the modification time
-r, --reference=FILE use this file's times instead of current time
-t STAMP use [[CC]YY]MMDDhhmm[.ss] instead of current time
--time=WORD change the specified time:
WORD is access, atime, or use: equivalent to -a
WORD is modify or mtime: equivalent to -m
--help display this help and exit
--version output version information and exit
Note that the -d and -t options accept different time-date formats.
GNU coreutils online help: <https://www.gnu.org/software/coreutils/>
Report touch translation bugs to <https://translationproject.org/team/>
Full documentation at: <https://www.gnu.org/software/coreutils/touch>
or available locally via: info '(coreutils) touch invocation'
【Comando Dos correspondiente】
Si no hay ningún archivo correspondiente con el mismo nombre, puede usar el comando copiar para crear un nuevo archivo vacío
copiar con newfile.txt necesita ingresar manualmente ctrl+Z y presionar enter.
Además, puede usar echo . >newfile.txt, este comando se implementa en un solo paso.
Tenga en cuenta que no debe haber espacios entre los símbolos de punto después del eco y los puntos se escribirán en el archivo si hay espacios .
C:\Users\hann>echo . > nuevoarchivo.txt
C:\Usuarios\hann>escriba nuevoarchivo.txt
C:\Users\hann>dir newfile.txt
El volumen en la unidad C es un
volumen de Windows con un número de serie 1E34-A256
C:\Users\directorio de Hann
26/08/2023 12:16 3 newfile.txt
1 archivo 3 bytes
0 directorios 123,609,210,880 bytes disponibles
Desventajas: crea archivos "vacíos" de bytes distintos de cero con líneas vacías
comando mv
mv: mueve o cambia el nombre de un archivo o directorio.
mv: Mover archivos o directorios, también se puede utilizar para cambiar el nombre. Por ejemplo, mv file1 file2
cambie el nombre file1
a file2
y elimine file1
.
Para mover un directorio y su contenido, es necesario utilizar -r
opciones como mv -r dir1 dir2
.
【Ayuda en inglés】
hann@HannYang:~$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed: resolve symbolic
links in DIR after processing instances of `..'
-P use the physical directory structure without following
symbolic links: resolve symbolic links in DIR before
processing instances of `..'
-e if the -P option is supplied, and the current working
directory cannot be determined successfully, exit with
a non-zero status
-@ on systems that support it, present a file with extended
attributes as a directory containing the file attributes
The default is to follow symbolic links, as if `-L' were specified.
`..' is processed by removing the immediately previous pathname component
back to a slash or the beginning of DIR.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
【Comando Dos correspondiente】
Mueva archivos y cambie el nombre de archivos y directorios.
Para mover al menos un archivo:
MOVE [/Y | /-Y] [unidad:][ruta]nombrearchivo1[,...] destino
Para cambiar el nombre de un directorio:
MOVE [/Y | /-Y] [unidad:][ruta]dirname1 dirname2
[unidad:][ruta]nombredearchivo1 Especifique la ubicación y el nombre del archivo que desea mover.
destino especifica la nueva ubicación del archivo. El destino puede consistir en una letra de unidad
y dos puntos, un nombre de directorio o una combinación. También puede incluir el nombre del archivo si solo va a mover un archivo
y cambiarle el nombre mientras lo mueve.
[unidad:][ruta]dirname1 Especifica el directorio cuyo nombre se va a cambiar.
dirname2 especifica el nuevo nombre del directorio.
/Y Suprime el mensaje para confirmar la sobrescritura de un archivo de destino existente.
/-Y Solicita confirmación para sobrescribir un archivo objeto existente.
El modificador de línea de comando /Y puede aparecer en la variable de entorno COPYCMD. Esto se puede
reemplazar con /-Y en la línea de comando. El valor predeterminado es solicitar
sobrescrituras a menos que el comando MOVE se ejecute desde un script por lotes.
Dos tiene otro comando ren para nombrar archivos por separado
Cambie el nombre del archivo.
RENOMBRAR [unidad:][ruta]nombre de archivo1 nombre de archivo2.
REN [unidad:][ruta]nombre de archivo1 nombre de archivo2.
Tenga en cuenta que no puede especificar una nueva unidad o ruta para el archivo de destino.
comando chmod
chmod: cambia los permisos de un archivo o directorio. Por ejemplo, chmod 755 file1
cambie file1
los permisos para que sean legibles, grabables y ejecutables.
【Ayuda en inglés】
hann@HannYang:~$ cd --help
cd: cd [-L|[-P [-e]] [-@]] [dir]
Change the shell working directory.
Change the current directory to DIR. The default DIR is the value of the
HOME shell variable.
The variable CDPATH defines the search path for the directory containing
DIR. Alternative directory names in CDPATH are separated by a colon (:).
A null directory name is the same as the current directory. If DIR begins
with a slash (/), then CDPATH is not used.
If the directory is not found, and the shell option `cdable_vars' is set,
the word is assumed to be a variable name. If that variable has a value,
its value is used for DIR.
Options:
-L force symbolic links to be followed: resolve symbolic
links in DIR after processing instances of `..'
-P use the physical directory structure without following
symbolic links: resolve symbolic links in DIR before
processing instances of `..'
-e if the -P option is supplied, and the current working
directory cannot be determined successfully, exit with
a non-zero status
-@ on systems that support it, present a file with extended
attributes as a directory containing the file attributes
The default is to follow symbolic links, as if `-L' were specified.
`..' is processed by removing the immediately previous pathname component
back to a slash or the beginning of DIR.
Exit Status:
Returns 0 if the directory is changed, and if $PWD is set successfully when
-P is used; non-zero otherwise.
【Comando Dos correspondiente】
Los atributos del sistema de archivos en ambos lados son diferentes, solo la función attrib es similar
Mostrar o cambiar las propiedades del archivo.
ATRIBUTO [+R | -R] [+A | -A] [+S | -S] [+H | -H] [+O | -O] [+yo | -Yo] [+X | -X] [+P | -P] [+U | -U]
[unidad:][ruta][nombre de archivo] [/S [/D]] [/L]
+ Establecer propiedades.
- Propiedades claras.
R Atributo de archivo de sólo lectura.
Propiedades del archivo de almacenamiento.
S Atributos del archivo del sistema.
H Ocultar atributos de archivo.
O Atributo sin conexión.
I Ningún atributo de archivo de índice de contenido.
X Sin atributo de archivo de limpieza.
V Atributo de integridad.
P Propiedad fija.
U es un atributo no fijo.
[unidad:][ruta][nombre de archivo]
especifica el archivo a procesar para el atributo. /S Procesa archivos coincidentes
en la carpeta actual y todas las subcarpetas . /D también procesa carpetas. /L Procesar enlaces simbólicos y atributos de destinos de enlaces simbólicos
Resumir
Los comandos básicos presentados anteriormente están básicamente disponibles en sistemas Dos y Linux y estar familiarizados con estos comandos puede ayudar a los usuarios a administrar sus propios archivos y directorios de manera más conveniente. Por supuesto también existen comandos para ver archivos, como el comando more, ambos sistemas tienen este comando, además el cat de linux corresponde al TIPO de dos.
En general, en comparación con Linux, los comandos externos son más abundantes, también hay comandos externos potentes como find, stat, grep, etc. que no tienen comandos correspondientes en Dos (a excepción de los pequeños no oficiales escritos por usted mismo). .