De DOS/Windows a Linux COMO Por Guido Gonzato, guido@ibogfs.cineca.it Traducido por Alvaro Alea v1.2.2, 31 October 1997. Traducion v0.1.0a, 20 de Enero de 1998 Este COMO esta dedicado a todos aquellos ( ¿ a quien si no ?) usuarios de DOS y Windows que se han armado de valor y decidico cambiar a Linux, El clonico libre de UNIX. Dadas las similitudes entre DOS y UNIX, el proposito de este documento es el de ayudar al lector a trasladar sus conocimientos del DOS y Windows al entorno de LINUX, para ser un productivo ASAP. 1. Introducion 1.1 ¿ Es linux para ti ? ¿ Quiere cambiar de DOS/Windows a Linux? buena idea, pero cuidado: Puede no serle util. IMHO, Hay cosas como "el mejor ordenador" o "el mejor sistema operativo" que dependen de lo que cada uno quiera hacer. He aqui el por que no creo que Linux sea la mejor para todo el mundo, aunque sea tecnicamente superior a muchos S.O. Se beneficiara enormemente de linux si lo que necesita es software para programar, Internet, TeX... sw tecnico en general, pero si comunmente necesita sw comercial, o si no se sientes bien aprendiendo y tecleando comandos, mire en otro lado. Linux no es ( por el momento ) tan facil de configurar como Windows o Mac, por lo que preparase para hackear un poco. En añadido a estos avisos , simplemente le dire de manera confidencial que si sigue y llega a ser un usuario de Linux 100% encontrara en el su Nirvana Computerizado. Depende de usted. Y recuerde que Linux + DOS/Windows pueden cohexistir en la misma maquina de todas formas. Prerequisitos para este COMO: Asumo que Conoce los comandos y conceptos basicos del DOS; Linux, posiblemente con X Windows System, esta adecuadamente instalado en su PC; Su shell - el equivalente al command.com - es bash; Comprende que esta quia es solo un primer paso, para mas informacion consulte los libros de Matt Welsh "Guia de Instalacion de Linux y primeros pasos" y/o el de Larry Greenfield "Guia del usuario de Linux" ( en www.infor.es/lucas o en version inglesa sunsite.unc.edu:/pub/linux/docs/LDP ). Este COMO remplaza al viejo mini-como "De DOS a linux - ¡Rapidamente!" .Notar ademas que sin especificarlo, toda la informacion de este trabajo esta dirigida hacia el DOS. Hay una seccion sobre Windows, pero hay que tener en cuenta que Linux y Windows son totalmente diferentes, a diferencia de DOS que esta un poco relacionado con UNIX. 1.2 Esta bien, Quiero mas Ha instalado Linux y los programas necesarios para su PC. Ha conseguido una cuenta como usuario para si ( y si no, ¡teclee adduser ahora!) y linux se esta ejecutando. Ha introducido su nombre y password, y ahora esta mirando a la pantalla y diciendo "Vale, ¿y ahora?" Ahora, no se altere, Esta casi preparado para hacer las mismas cosas que hacia con DOS, y muchas mas, Si estuviese ejecutando DOS en lugar de linux, deberia estar haciendo algunas de las siguientes tareas: ejecutar programas y crear, copiar, ver, borrar, renombrar ficheros; CDear, MDear, RDear, y DIRear tus directorios; formatear discos y copiar ficheros a y desde ellos; ajustar su AUTOEXEC.BAT y CONFIG.SYS; escribir sus propios ficherso .BAT y/o programas QBASIC; el 1% restante. Ya deberia saber que estas tareas se pueden realizar bajo Linux de una manera similar a DOS, Bajo DOS, los usuarios avanzados usan muy pocos de los mas de 100 comandos disponibles, lo mismo a este punto se puede aplicar a Linux. Unas pocas cosas a tener en cuenta antes de seguir: Primero, como acabar, para quitar Linux: si esta viendo la pantalla en modo texto, pulse CTRL-ALT-SUPR y espere a que es sistema acabe y le diga que todo esta bien, entonces apaque el ordenador. Si esta trabajando bajo X, pulse CTRL-ALT-BORRAR primero, luego CTRL-ALT-SUPR. Nunca apage o resetee el ordenador directamente: podria dañar su sistema de ficheros; A diferencia del DOS, Linux incluye mecanismos de seguiridad, debido a su naturaleza multiusuario, ficheros y directorios tiene permisos asociados, y por ello algunos no pueden ser acedidos por el usuario normal; ( ver la seccion permisos ). Solo el usuario cuyo nombre es "root" tiene el poder ( Este chico es el administrador del sistema. Si trabajas en tu propio PC, Tu eres el root.) DOS, por lo contrario te permite un aceso sin restrinciones a todo el ordenador. Es altamente recomendable que esperimente, juege, pruebe por si mismo: no se hara daño. Si necesita ayuda pude hacer lo siguiente: Para conseguir ayuda de los "comandos internos" del shell, teclee help; Para conseguir ayuda de un comando, teclee man comando que invoca al manual "las paginas man" asociado al comando. Info es un sistema de documentacion basado en hypertexto, quiza no muy intuitivo de usar al principio. Finalmente puede probar apropos comando o whatis comando, pulsado q para salir; Gran parte de la potencia y flexibilidad de UNIX viene del conceptos tan simples como la redirecion y las tuberias, mucho mas potentes que bajo DOS. Simples comandos pueden ser combinados para realizar juntos complicadas tareas. ¡Utilize estas caracteristicas! Convenciones: <...> significa que algo debe ser especificado, mientras [...] significa que algo es opcional. Ejemplo: $ tar -tf [> fichero_a_redirigir] archivo.tar debe ser indicado. pero la redirecion a fichero_a_redirigir es opcional. De ahora en adelante "RPM" significa "por favor, lea las paginas man para mayor informacion" ( N.d.T. quiza "Revise el P*t* Manual"). 1.3 Para los impacientes ¿Por donde empezar? hechele un vistazo a esto: DOS Linux Notas --------------------------------------------------------------------------- BACKUP tar -Mcvf device dir/ completamente distinto CD dirname\ cd dirname/ casi la misma sintasis COPY file1 file2 cp file1 file2 idem DEL file rm file cuidado no hay undelete DELTREE dirname rm -R dirname/ lo mismo DIR ls no es exactamente igual DIR file /S find . -name file completamente distinto EDIT file vi file creo que no te ba a gustar emacs file este es mejor jstar file parece el edit del DOS FORMAT fdformat, mount, umount sintasis bastante distinta HELP command man command misma filosofia MD dirname mkdir dirname/ casi la misma sintasis MOVE file1 file2 mv file1 file2 idem NUL /dev/null idem PRINT file lpr file idem PRN /dev/lp0, /dev/lp1 idem RD dirname rmdir dirname/ casi la misma sitasis REN file1 file2 mv file1 file2 no vale para varios fiche. RESTORE tar -Mxpvf device diferente sintasis TYPE file less file mucho mejor WIN startx ¡es caso aparte! Si necesitas mas que una tabla de comandos, por favor lee las siguientes secciones. 2. Ficheros y programas 2.1 Ficheros: Nociones preliminares Linus tiene un sistema de ficheros - significa que "la estructura de directorios y ficheros esta en el" - muy similar a la del dos, los ficheros tiene nombre de archivo, que obedece unas reglas especiales, almacenados en directorios, algunos son ejecutables, y muchos de estos tiene parametros, Ademas puedes usar caracteres comodin, redireciones y tuberias, solo hay unas pequeñas diferencias. Bajo DOS, los nombres de fichero son nombrados bajo la llamada forma de 8.3, e.j. NOTAGORD.TXT. Bajo linus podemos hacerlo mejor. Si instala Linux usando un sistema de ficheros como ext2 o umsdos,puede usar nombres de fichero largos, ( hasta 255 caracteres ) y con mas de un punto en ellos: por ejemplo Este_es.un.MUY_largo.nombre Note que se puden usar letras mayusculas y minusculas, de echo... las letras mayusculas y minusculas son diferentes, es decir NOMBREDEFICHERO.tar.gz y nombredefichero.tar.gz son dos ficheros diferentes. ls es un comando, LS es un error; Los usuarios de windows 95 querran usar ficheros con nombre largos, bajo linux por supuesto. Si un fichero contiene espacios ( no es recomendable, pero si posible ), debe encerrar el fichero en dobles comillas cuando se refiera a el. por ejemplo: $ # El siguiente comando crea un directorio llamado mis viejos ficheros $ mkdir "Mis viejos ficheros" $ ls Mis viejos ficheros bin tmp Algunos caracteres no deberian pero pueden ser utilizados: algunos son !*$&. No voy a decirte por que, no obstante. No hay una norma de extensiones como .COM y .EXE para los programas o .BAT para los ficheros de proceso por lotes. Los ficherso ejecutables son marcados con un asterisco '*' al final de su nombre cuando ejecuta el comando ls -F. Por ejemplo: $ ls -F I_am_a_dir/ cindy.jpg cjpg* letter_to_Joe my_1st_script* old~ Los ficheros cjpg* y mi_1er_script* son ejecutables --- "programas". Bajo dos, los ficheros copia de seguirdad sielen acabar el .BAK, bajo linux suelen acabar en una tilde ~. Asi mismo los ficheros que comienzan con . se consideran ocultos. Por ejemplo: el fichero .Soy.oculto no sera mostrado despues de ejecutar el comando ls; En DOS las opciones son indicadas con /losquesea, las opciones en Linux son con -loquesea. Ejemplo: dir /s se convierte en ls -R. note que muchos programas DOS como PKZIP o ARJ, usan el estilo UNIX para las opciones. Puede saltar ahora a la secion de trasladar comandos de DOS a linux, pero deberias leer esto. 2.2 Link simbolicos UNIX tiene un tipo de ficheros que no existe bajo DOS: los link Sinbolicos. Estos pueden ser punteros a ficheros o a directorios, y pueden ser usados en lugar del fichero o directorio al que apuntan; parecido a los acesos directos de Windows 95. Ejemplos de Link simbolicos son /usr/X11, que apunta a /usr/X11R6; /dev/modem, que apunta a /dev/cua0 o quiza /dev/cua1. Para hacer un link simbolico: $ ln -s Ejemplo: $ ln -s /usr/doc/g77/DOC g77manual.txt Ahora puedes referirte a g77manual.txt en ligar de /usr/doc/g77/DOC. Los links aparecen en las listas de directorios como sigue: $ ls -F g77manual.txt@ $ ls -l (varias cosas...) g77manual.txt -> /usr/doc/g77/DOC 2.3 Permisos y pertenencias Los ficheros y directorios de DOS tienen los siguientes atributos A (archivo), H (oculto), R (solo lectura), y S (sistema). Solo H y R tienen sentido bajo Linux: los ficheros ocultos empiezan con un punto, y para el atributo R, lea lo siguiente: Bajo UNIX un fichero tiene "permisos" y un dueño, que pertenece a un "grupo". Mira el siguiente ejemplo: $ls -l /bin/ls -rwxr-xr-x 1 root bin 27281 Aug 15 1995 /bin/ls* El primer campo contiene los permisos del fichero /bin/ls, que pertenece al root y que esta en el grupo bin. Sin estendernos demasiado ( el libro de Matt esta para eso), recordar que -rwxr-xr-x significa de izquierda a derecha: - es el tipo de fichero ( - = normal, d = directorio, l = link , etc),rwx son los permisos para el dueño ( lectura, escritura y ejecutable) r-x son los permisos para el grupo del fichero (lectura, ejecutable); (no voy a cubrir el concepto de grupo, podra sobrevivir sin el si es un principiante ;-) r-x son los otros permisos para el resto de usuarios (lectura, ejecutable). Esto es por que no podra borrar el fichero /bin/ls a menos que sea root: no tiene permiso de escritura para hacerlo. Para cambiar los permisos del fichero, el comando es: $ chmod Donde quien es u (usuario, el dueño), g (grupo), o (otros), X puede ser + p -, y perm es r (lectura), w (escritura) o x (ejecutable). Ejemplos: $ chmod u+x fichero Esto activa los permisos de ejecucion para el poseedor del fichero. Abreviatura: chmod -x fichero $ chmod go-wx fichero Esto elimina los permisos de escritura y ejecucion para quien no sea el dueño. $ chmod ugo+rwx file Esto da a todo el mundo permisos de lectura, escritura y ejecucion. # chmod +s file Esto hace el llamado "setuid" o fichero "suid" ---- un fichero que cualquiera puede ejecutar como si tuviese privilegios del dueño. Una manera corta de referirse a permisos es por numeros rwxr-xr-x puede ser expresado como 7555 ( cada letra corresponde a un bit: --- es 9, --x es 1, -w- es 2, -wx es 3...). Puede parecer dificil, pero con un poco de practica podra comprender el concepto. El root, tambien llamado superusuario, puede cambiar los permisos de cualquier fichero, y mucho mas , RMP. 2.4 Traduciendo comandos de DOS a Linux En la izquierda el comando DOS; en la derecha su respectivo en Linux. COPY: cp DEL: rm MOVE: mv REN: mv TYPE: more, less, cat Operadores de redirecion y tuberias: < > >> | Comodines: * ? nul: /dev/null prn, lpt1: /dev/lp0 or /dev/lp1; lpr - EJEMPLOS - DOS Linux --------------------------------------------------------------------- C:\GUIDO>COPY JOE.TXT JOE.DOC $ cp joe.txt joe.doc C:\GUIDO>COPY *.* TOTAL $ cat * > total C:\GUIDO>COPY FRACTALS.DOC PRN $ lpr fractals.doc C:\GUIDO>DEL TEMP $ rm temp C:\GUIDO>DEL *.BAK $ rm *~ C:\GUIDO>MOVE PAPER.TXT TMP\ $ mv paper.txt tmp/ C:\GUIDO>REN PAPER.TXT PAPER.ASC $ mv paper.txt paper.asc C:\GUIDO>PRINT LETTER.TXT $ lpr letter.txt C:\GUIDO>TYPE LETTER.TXT $ more letter.txt C:\GUIDO>TYPE LETTER.TXT $ less letter.txt C:\GUIDO>TYPE LETTER.TXT > NUL $ cat letter.txt > /dev/null n/a $ more *.txt *.asc n/a $ cat section*.txt | less Notas: * is mas amplio bajo linux: * coincide con todos los ficheros escepto los ocultos; .* coincide con todos los ficheros ocultos; *.* coincide solo con aquellos que tienen un '.' en la mitad, seguido de mas caracteres; p*r coincide con 'peter' y con 'piper'; *c* coincide con 'picked' y con 'peck'; Cuando use more, pulse SPACIO para leer otro trozo de fichero, 'q' o Ctrl-C para salir. less es mas intuituvo y le permite utilizar las teclas del cursor; No hay UNDELETE, por lo que pienselo bien dos veces antes de borrar cualquier cosa; Ademas de los < > >> del DOS, Linux tiene 2> para rediriguir los mensajes de erro (stderr); ademas 2>&1 redirige stderr a stdout, mientras que 1>&2 redirige stdout a stderr; Linux tiene otro comodin; los []. Uso: [abc]* coincide con cualquier fichero que empieze por a,b o c;*[I-N,1,2,3] coincide con cualquier fichero que acabe en I, J, K, L, M, N, 1, 2, 3; No hay un RENAME como el del dos; es decir, mv *.xxx *.yyy no funciona. Podia provar el siguiente script; lea la secion Shell Scripts para mas detalles. #!/bin/sh # ren: renombra multiples ficheros en funcion de ciertas reglas if [ $# -lt 3 ] ; then echo "uso: ren \"mascara\" \"remplazar\" ficheros..." exit 1 fi OLD=$1 ; NEW=$2 ; shift ; shift for file in $* do new=`echo ${file} | sed s/${OLD}/${NEW}/g` mv ${file} $new done Cuidado: esto no es como le REN del dos,, usa "expresiones regulares" que no tiene por que saber que son, rapidamente, si simplemente desea cambiar la extension de un fichero, uselo asi: ren "htm$" "html" *htm .No se olvide del signo $. Use cp -i y mv -i para ser avisado antes de sobreescribir un fichero. 2.5 Ejecutando programas: Multitarea u sessiones Para ejecutar un programa, teclee su nombre como lo haria bajo DOS. Si el directorio (seccion directorios) donde el programa esta almacenado se encuentra en el PATH (seccion Inicializacion del Systema), el programa se ejecutara. Escepcion: a diferencia del DOS, bajo linux los programas que estan en el directorio actual no se ejecutan a menos que ese directorio este incluido en el path. Solucion: siendo prog su programa, teclee ./prog Esto es como seria una tipica linea de comandos: $ comando -s1 -s2 ... -sn par1 par2 ... parn < input > output Donde -s1, .... -sn son las opciones del programa, par1, ..., par2 son los parametros del programa, puedes ejecutar varios programas en una linea: $ comando1 ; comando2 ; comando3 Que es todo lo necesario para ejecutar programas, pero es facil ir un paso mas alla. Una de las principales razones para usar Linux es que es un sistema operativo multitarea --- puede ejecutar varios progamas ( de ahora en adelante, procesos ) al mismo tienpo. Puede lanzar un proceso en segundo plano, y continuar trabajando normalmente, Adenas, Linux le permite tener varias sessiones: ¡es como tener varios ordenadores trabajando a la vez! Para cambiar entre las sesiones 1..6: $ ALT-F1 ... ALT-F6 Para iniciar una nueva session son salir de la actual: $ su - Ejemplo: $ su - root Esto es util, por ejemplo, cuando necesite montar un disco (seccion disquetes): normalmente, solo el root puede hacer esto. Para terminar una sesion: $ exit Si esiste algun trabajo parado ( ver mas adelante) sera avisado. Para lanzar un proceso en primer plano: $ progname [-switches] [parameters] [< input] [> output] Para lanzar un proceso en segundo plano, añada un ampersand '&' al final de la linea: $ progname [-switches] [parameters] [< input] [> output] & [1] 123 El shell identifica el proceso con un numero de trabajo (ej. [1]; ver despues). y con un PID (123 en el ejemplo). Para ver cuantos procesos hay: $ ps -a Esto sacara una lista de los procesos actualmente ejecutandose. Para matar un proceso: $ kill Puedes necesitar matar un proceso cuando no conoces como quitarlo por el metodo correcto... ;-), a veces un proceso solo puede ser cambiado por uno de los siguientes: $ kill -15 $ kill -9 Ademas de esto, el shell le permite parar o temporarmente suspender un proceso, enviarlo a segundo plano, y pasar un proceso de segundo plano a primer plano. En este contexto proceso es lo mismo que Trabajo" Para ver cuando tabajos hay: $ jobs Aqui los trabajos son identificados por su numero de trabajo, no por su PID. Para parar un proceso ejecutandose en primer plano ( esto no siempre funciona ): $ CTRL-C Para suspender un proceso ejecutandose en primer plano (idem): $ CTRL-Z Para enviar un proceso a sengundo plano ( y convertirlo en trabajo): $ bg Para pasar un trabajo a primer plano: $ fg Para matar un trabajo $ kill <%trabajo> Donde puede ser 1, 2, 3, ... Usando estos comandos puede formatear un disco, comprimir ficheros, compilar un programa, y descomprimir un archivo, y todo al mismo tiempo, y seguira teniendo el prompt a su disposicion. ¡Prueve esto bajo DOS! y Pruevelo bajo WIndows, vera que diferencia de prestaciones. 2.6 Ejecutando programas en Ordenadores Remotos To run a program on a remote machine whose IP address is remote.bigone.edu, you do: $ telnet remote.bigone.edu After logging in, start your favourite program. Needless to say, you must have an account on the remote machine. If you have X11, you can even run an X application on a remote computer, displaying it on your X screen. Let remote.bigone.edu be the remote X computer and local.linux.box be your Linux machine. To run from local.linux.box an X program that resides on remote.bigone.edu, do the following: fire up X11, start an xterm or equivalent terminal emulator, then type: $ xhost +remote.bigone.edu $ telnet remote.bigone.edu after logging in, type: remote:$ DISPLAY=local.linux.box:0.0 remote:$ progname & (instead of DISPLAY..., you may have to write setenv DISPLAY local.linux.box:0.0. It depends on the remote shell.) Et voila! Now progname will start on remote.bigone.edu and will be displayed on your machine. Don't try this over a ppp line though, for it's too slow to be usable 3. Using Directories 3.1 Directories: Preliminary Notions We have seen the differences between files under DOS and Linux. As for directories, under DOS the root directory is \, under Linux / is. Similarly, nested directories are separated by \ under DOS, by / under Linux. Example of file paths: DOS: C:\PAPERS\GEOLOGY\MID_EOC.TEX Linux: /home/guido/papers/geology/mid_eocene.tex As usual, .. is the parent directory, . is the current directory. Remember that the system won't let you cd, rd, or md everywhere you want. Each user starts from his or her own directory called 'home', given by the system administrator; for instance, on my PC my home dir is /home/guido. 3.2 Directories Permissions Directories, too, have permissions. What we have seen in Section Permissions holds for directories as well (user, group, and other). For a directory, rx means you can cd to that directory, and w means that you can delete a file in the directory (according to the file's permissions, of course), or the directory itself. For example, to prevent other users from snooping in /home/guido/text: $ chmod o-rwx /home/guido/text 3.3 Translating Commands from DOS to Linux DIR: ls, find, du CD: cd, pwd MD: mkdir RD: rmdir DELTREE: rm -R MOVE: mv - EXAMPLES - DOS Linux --------------------------------------------------------------------- C:\GUIDO>DIR $ ls C:\GUIDO>DIR FILE.TXT $ ls file.txt C:\GUIDO>DIR *.H *.C $ ls *.h *.c C:\GUIDO>DIR/P $ ls | more C:\GUIDO>DIR/A $ ls -l C:\GUIDO>DIR *.TMP /S $ find / -name "*.tmp" C:\GUIDO>CD $ pwd n/a - see note $ cd ditto $ cd ~ ditto $ cd ~/temp C:\GUIDO>CD \OTHER $ cd /other C:\GUIDO>CD ..\TEMP\TRASH $ cd ../temp/trash C:\GUIDO>MD NEWPROGS $ mkdir newprogs C:\GUIDO>MOVE PROG .. $ mv prog .. C:\GUIDO>MD \PROGS\TURBO $ mkdir /progs/turbo C:\GUIDO>DELTREE TEMP\TRASH $ rm -R temp/trash C:\GUIDO>RD NEWPROGS $ rmdir newprogs C:\GUIDO>RD \PROGS\TURBO $ rmdir /progs/turbo Notes: 1.when using rmdir, the directory to remove must be empty. To delete a directory and all of its contents, use rm -R (at your own risk). 2.the character '~' is a shortcut for the name of your home directory. The commands cd or cd ~ will take you to your home directory from wherever you are; the command cd ~/tmp will take you to /home/your_home/tmp. 3.cd - ``undoes'' the last cd. 4. Floppies, Hard Disks, and the Like 4.1 Managing Devices You have never thought about it, but the DOS command FORMAT A: does a lot more work than it seems. In fact, when you issue the command FORMAT it will: 1) physically format the disk; 2) create the A:\ directory (= create a filesystem); 3) make the disk available to the user (= mount the disk). These three steps are addressed separately under Linux. You can use floppies in MS-DOS format, though other formats are available and are better---the MS-DOS format won't let you use long filenames. Here is how to prepare a disk (you'll need to start a session as root): To format a standard 1.44 meg floppy disk (A:): # fdformat /dev/fd0H1440 To create a filesystem: # mkfs -t ext2 -c /dev/fd0H1440 To create an MS-DOS filesystem, use msdos instead of ext2. Before using the disk, you must mount it. To mount the disk: # mount -t ext2 /dev/fd0 /mnt or # mount -t msdos /dev/fd0 /mnt Now you can address the files in the floppy. When you've finished, before extracting the disk you must unmount it. To unmount the disk: # umount /mnt Now you can extract the disk. Obviously, you have to fdformat and mkfs only unformatted disks, not previously used ones. If you want to use drive B:, refer to fd1H1440 and fd1 instead of fd0H1440 and fd0 in the examples above. All you used to do with A: or B: is now done using /mnt instead. Examples: DOS Linux --------------------------------------------------------------------- C:\GUIDO>DIR A: $ ls /mnt C:\GUIDO>COPY A:*.* $ cp /mnt/* /docs/temp C:\GUIDO>COPY *.ZIP A: $ cp *.zip /mnt/zip C:\GUIDO>A: $ cd /mnt A:>_ /mnt/$ _ If you don't like this mounting/unmounting thing, use the mtools suite: it's a set of commands that are perfectly equivalent to their DOS counterpart, but start with an `m': i.e., mformat, mdir, mdel, and so on. They can even preserve long file names, but not file permissions. Use these commands as you'd use the DOS commands and rest in peace. Needless to say, what holds for floppies also holds for other devices; for instance, you may want to mount another hard disk or a CD-ROM drive. Here's how to mount the CD-ROM: # mount -t iso9660 /dev/cdrom /mnt This was the ``official'' way to mount your disks, but there's a trick in store. Since it's a bit of a nuisance having to be root to mount a floppy or a CD-ROM, every user can be allowed to mount them this way: as root, do the following: ~# mkdir /mnt/a: ; mkdir /mnt/a ; mkdir /mnt/cdrom ~# chmod 777 /mnt/a* /mnt/cd* ~# # make sure that the CD-ROM device is right ~# chmod 666 /dev/hdb ; chmod 666 /dev/fd* add in /etc/fstab the following lines: /dev/cdrom /mnt/cdrom iso9660 ro,user,noauto 0 0 /dev/fd0 /mnt/a: msdos user,noauto 0 0 /dev/fd0 /mnt/a ext2 user,noauto 0 0 Now, to mount a DOS floppy, an ext2 floppy, and a CD-ROM: $ mount /mnt/a: $ mount /mnt/a $ mount /mnt/cdrom /mnt/a, /mnt/a:, and /mnt/cdrom can now be accessed by every user. Remember that allowing everyone to mount disks this way is a gaping security hole, if you care. 4.2 Backing Up Now that you know how to handle floppies etc., a couple of lines to see how to do your backup. There are several packages to help you, but the very least you can do for a multi-volume backup is (as root): # tar -M -cvf /dev/fd0H1440 dir_to_backup/ Make sure to have a formatted floppy in the drive, and several more ready. To restore your stuff, insert the first floppy in the drive and do: # tar -M -xpvf /dev/fd0H1440 5. ¿Y que hay sobre Windows? El "equivalente" a windows es el sistema grafico X11, a diferencia de Windows o MAC, X11 no fue diseñado para ser bonito o facil de usar, solo para proporcionar unas facilidades graficas a las estaciones de trabajo UNIX. Estas son las principales diferencias: Mientras que el aspecto de Windows es comun para todo el mundo, en X11 no es asi: es mucho mas configurable. El aspecto general de X11 es dado por un componente llamado "administrador de ventanas"; hay muchos entre los que podra eleguir, El mas comun es fvwm, basico, pero bonito y eficiente en gasto de memoria, fvwm95 y The Next Level dan a X11 un aspecto de Windows 95, hay mas, algunos dan un aspecto realmente bonito; Su administrador de ventanas puede ser configurado para que una ventana actue como en windows, si hace click sobre ella esta ira al primer plano. Otra posibilidad es que esta pase al primer plano cuando el raton este encima de ella. Esta caracteristica ("foco") y muchas otras pueden ser modificadas editando uno o mas ficheros de configuracion. Lea la documentacion de su administrador de ventanas; X applications are written using special libraries (``widget sets''); as several are available, applications look different. The most basic ones are those that use the Athena widgets (2--D look; xdvi, xman, xcalc); others use Motif (netscape), others still use Tcl/Tk, XForms, Qt and what have you. Some---not all---of these libraries provide roughly the same look and feel as Windows; so much for the look of X11, but what about the feel? Unfortunately, all applications behave differently. For instance, if you select a line of text using the mouse and press BACKSPACE, you'd expect the line to disappear, right? This doesn't work with Athena--based apps, but it does with Motif, Qt, and Tcl/Tk ones; scrollbars, resizing, and iconisation: these, too, depend on the window manager and the widget set. Too many different things to mention here, just a couple of points. When using Athena--based apps the scrollbars are better moved with the central button. If you don't have a three--button mouse, try pressing the two buttons together; applications don't have an icon by default, but they can have many. It depends on the window manager. The desktop is called ``root window'', and you can change its appearance with apps like xsetroot or xloadimage; the clipboard can only contain text, and behaves strange. Once you've selected text, it's already copied to the clipboard: move elsewhere and press the central button. There's an application, xclipboard, that provides for multiple clipboard buffers; drag and drop is an option, and is only available if you use X applications that support it. To save memory, it's better to use applications that use the same libraries, but this is difficult to do in practice. There's a project called the K Desktop Environment that aims at making X11 look and behave as coherently as Windows; it's currently in early beta stage but, believe me, it's awesome. It's going to put Windows' interface to shame. Point your browser to http://www.kde.org. 6. Tailoring the System 6.1 System Initialisation Files Two important files under DOS are AUTOEXEC.BAT and CONFIG.SYS, which are used at boot time to initialise the system, set some environment variables like PATH and FILES, and possibly launch a program or batch file. Under Linux there are several initialisation files, some of which you had better not tamper with until you know exactly what you are doing. I'll tell you what the most important are, anyway: FILES NOTES /etc/inittab don't touch for now! /etc/rc.d/* ditto If all you need is setting the $PATH and other environment variables, or you want to change the login messages or automatically launch a program after the login, have a look at the following files: FILES NOTES /etc/issue sets pre-login message /etc/motd sets post-login message /etc/profile sets $PATH and other variables, etc. /etc/bashrc sets aliases and functions, etc. /home/your_home/.bashrc sets your aliases + functions /home/your_home/.bash_profile or /home/your_home/.profile sets environment + starts your progs If the latter file exists (note that it is a hidden file), it will be read after the login and the commands in it will be executed. Example---look at this .bash_profile: # I am a comment echo Environment: printenv | less # equivalent of command SET under DOS alias d='ls -l' # easy to understand what an alias is alias up='cd ..' echo "I remind you that the path is "$PATH echo "Today is `date`" # use the output of command 'date' echo "Have a good day, "$LOGNAME # The following is a "shell function" ctgz() # List the contents of a .tar.gz archive. { for file in $* do gzip -dc ${file} | tar tf - done } # end of .profile $PATH and $LOGNAME, you guessed right, are environment variables. There are many others to play with; for instance, RMP for apps like less or bash. 6.2 Program Initialisation Files Under Linux, virtually everything can be tailored to your needs. Most programs have one or more initialisation files you can fiddle with, often as a .prognamerc in your home dir. The first ones you'll want to modify are: .inputrc: used by bash to define keybindings; .xinitrc: used by startx to initialise X Window System; .fvwmrc: used by the window manager fvwm. A sample is in: /usr/lib/X11/fvwm/system.fvwmrc; .Xdefault: used by rxvt, a terminal emulator for X, and other programs. For all of these and the others you'll come across sooner or later, RMP. 7. A Bit of Programming 7.1 Shell Scripts: .BAT Files on Steroids If you used .BAT files to create shortcuts of long command lines (I did a lot), this goal can be attained by inserting appropriate alias lines (see example above) in profile or .profile. But if your .BATs were more complicated, then you'll love the scripting language made available by the shell: it's as powerful as QBasic, if not more. It has variables, structures like while, for, case, if... then... else, and lots of other features: it can be a good alternative to a ``real'' programming language. To write a script---the equivalent of a .BAT file under DOS---all you have to do is write a standard ASCII file containing the instructions, save it, then make it executable with the command chmod +x . To execute it, type its name. A word of warning. The system editor is called vi, and in my experience most new users find it very difficult to use. I'm not going to explain how to use it, because I don't like it and don't use it, so there. See Matt Welsh's ``Linux installation...'', pag. 109. (You had better get hold of another editor like joe, jed or emacs for X.) Suffice it here to say that: to insert some text, type 'i' then your text; to quit vi whithout saving, type ESC then :q! to save and quit, type ESC then :wq Writing scripts under bash is such a vast subject it would require a book by itself, and I will not delve into the topic any further. I'll just give you an example of shell script, from which you can extract some basic rules: #!/bin/sh # sample.sh # I am a comment # don't change the first line, it must be there echo "This system is: `uname -a`" # use the output of the command echo "My name is $0" # built-in variables echo "You gave me the following $# parameters: "$* echo "The first parameter is: "$1 echo -n "What's your name? " ; read your_name echo notice the difference: "hi $your_name" # quoting with " echo notice the difference: 'hi $your_name' # quoting with ' DIRS=0 ; FILES=0 for file in `ls .` ; do if [ -d ${file} ] ; then # if file is a directory DIRS=`expr $DIRS + 1` # DIRS = DIRS + 1 elif [ -f ${file} ] ; then FILES=`expr $FILES + 1` fi case ${file} in *.gif|*jpg) echo "${file}: graphic file" ;; *.txt|*.tex) echo "${file}: text file" ;; *.c|*.f|*.for) echo "${file}: source file" ;; *) echo "${file}: generic file" ;; esac done echo "there are ${DIRS} directories and ${FILES} files" ls | grep "ZxY--!!!WKW" if [ $? != 0 ] ; then # exit code of last command echo "ZxY--!!!WKW not found" fi echo "enough... type 'man bash' if you want more info." 7.2 C for Yourself Under UNIX, the system language is C, love it or hate it. Scores of other languages (FORTRAN, Pascal, Lisp, Basic, Perl, awk...) are also available. Taken for granted that you know C, here are a couple of guidelines for those of you who have been spoilt by Turbo C++ or one of its DOS kin. Linux's C compiler is called gcc and lacks all the bells and whistles that usually accompany its DOS counterparts: no IDE, on-line help, integrated debugger, etc. It's just a rough command-line compiler, very powerful and efficient. To compile your standard hello.c you'll do: $ gcc hello.c which will create an executable file called a.out. To give the executable a different name, do $ gcc -o hola hello.c To link a library against a program, add the switch -l. For example, to link in the math library: $ gcc -o mathprog mathprog.c -lm (The -l switch forces gcc to link the library /usr/lib/lib.a; so -lm links /usr/lib/libm.a). So far, so good. But when your prog is made of several source files, you'll need to use the utility make. Let's suppose you have written an expression parser: its source file is called parser.c and #includes two header files, parser.h and xy.h. Then you want to use the routines in parser.c in a program, say, calc.c, which in turn #includes parser.h. What a mess! What do you have to do to compile calc.c? You'll have to write a so-called makefile, which teaches the compiler the dependencies between sources and objects files. In our example: # This is makefile, used to compile calc.c # Press the key at appropriate positions! calc: calc.o parser.o gcc -o calc calc.o parser.o -lm # calc depends on two object files: calc.o and parser.o calc.o: calc.c parser.h gcc -c calc.c # calc.o depends on two source files parser.o: parser.c parser.h xy.h gcc -c parser.c # parser.o depends on three source files # end of makefile. Save this file as makefile and type make to compile your program; alternatively, save it as calc.mak and type make -f calc.mak, and of course RMP. You can invoke some help about the C functions, that are covered by man pages, section 3; for example, $ man 3 printf There are lots of libraries available out there; among the first you'll want to use are ncurses, to handle textmode effects, and svgalib, to do graphics. If you feel brave enough to tackle X programming, get XForms ( ftp://bloch.phys.uwm.edu/pub/xforms) and/or one of the many libraries that make writing X programs a breeze. Have a look at http://www.xnet.com/~blatura/linapp6.html . Many editors can act as an IDE; emacs and jed, for instance, also feature syntax highlighting, automatic indent and so on. Alternatively, get the package rhide from sunsite.unc.edu:/pub/Linux/devel/debuggers/. It's a Borland IDE clone, and chances are that you'll like it. 8. The Remaining 1% 8.1 Using tar & gzip Under UNIX there are some widely used applications to archive and compress files. tar is used to make archives---it's like PKZIP but it doesn't compress, it only archives. To make a new archive: $ tar -cvf [file...] To extract files from an archive: $ tar -xpvf [file...] To list the contents of an archive: $ tar -tf | less You can compress files using compress, which is obsolete and shouldn't be used any more, or gzip: $ compress $ gzip that creates a compressed file with extension .Z (compress) or .gz (gzip). These programs can compress only one file at a time. To decompress, use: $ compress -d $ gzip -d RMP. The unarj, zip and unzip (PK??ZIP compatible) utilities are also available. Files with extension .tar.gz or .tgz (archived with tar, then compressed with gzip) are as common in the UNIX world as .ZIP files are under DOS. Here's how to list the contents of a .tar.gz archive: $ gzip -dc | tar tf - | less or, equivalently, $ tar -ztf | less 8.2 Installing Applications First of all: installing packages is root's work. Some Linux applications are distributed as .tar.gz or .tgz archives, specifically prepared so that they can be decompressed from / typing the following command: # gzip -dc | tar xvf - or, equivalently, $ tar -zxf The files will be decompressed in the right directory, which will be created on the fly. Users of the Slackware distribution have a user-friendly pkgtool program; another is rpm, which is available on all distributions thanks to Red Hat. Most programs shouldn't be installed from /; typically, the archive will contain a directory called pkgname/ and a lot of files and/or subdirectories under pkgname/. A good rule is to install those packages from /usr/local. Besides, some programs are distributed as C or C++ source files, which you'll have to compile to create the binaries. In most cases, all you have to do is issue make. Obviously, you'll need the gcc or g++ compiler. 8.3 Tips You Can't Do Without Command completion: pressing when issuing a command will complete the command line for you. Example: you have to type gcc this_is_a_long_name.c; typing gcc thi will suffice. (If you have other files that start with the same characters, supply enough characters to resolve any ambiguity.) Backscrolling: pressing SHIFT + PAG UP (the grey key) allows you to backscroll a few pages, depending on how much video memory you have. Resetting the screen: if you happen to more or cat a binary file, your screen may end up full of garbage. To fix things, blind type reset or this sequence of characters: echo CTRL-V ESC c RETURN. Pasting text: in console, see below; in X, click and drag to select the text in an xterm window, then click the middle button (or the two buttons together if you have a two-button mouse) to paste. There is also xclipboard (alas, only for text); don't get confused by its very slow response. Using the mouse: install gpm, a mouse driver for the console. Click and drag to select text, then right click to paste the selected text. It works across different VCs. Messages from the kernel: have a look at /var/adm/messages or /var/log/messages as root to see what the kernel has to tell you, including bootup messages. The command dmesg is also handy. 8.4 Useful Programs and Commands This list reflects my personal preferences and needs, of course. First of all, where to find them. Since you all know how to surf the Net and how to use archie and ftp, I'll just give you three of the most important addresses for Linux: ftp://sunsite.unc.edu, ftp://tsx-11.mit.edu, and ftp://nic.funet.fi. Please use your nearest mirror. at allows you to run programs at a specified time; awk is a simple yet powerful language to manipulate data files (and not only). For example, being data.dat your multi field data file, $ awk '$2 ~ "abc" {print $1, "\t", $4}' data.dat prints out fields 1 and 4 of every line in data.dat whose second field contains ``abc''. cron is useful to perform tasks periodically, at specified date and time; delete-undelete do what their name means; df gives you info about all mounted disk(s); dosemu allows you to run several (not all) DOS programs---including Windows 3.x, with a bit of hacking; file tells you what filename is (ASCII text, executable, archive, etc.); find (see also Section dir) is one of the most powerful and useful commands. It's used to find files that match several characteristics and perform actions on them. General use of find is: $ find where includes search criteria and actions. Examples: $ find . -type l -exec ls -l {} \; finds all the files that are symbolic links and shows what they point to. $ find / -name "*.old" -ok rm {} \; finds all the files matching the pattern and deletes them, asking for your permission first. $ find . -perm +111 finds all the files whose permissions match 111 (executable). $ find . -user root finds all the files that belong to root. Lots of possibilities here---RMP. gnuplot is a brilliant program for scientific plotting; grep finds text patterns in files. For example, $ grep -l "geology" *.tex lists the files *.tex that contain the word ``geology''. The variant zgrep works on gzipped files. RMP; tcx compresses executable binaries keeping them executable; joe is an excellent editor. Invoking it by typing jstar you'll get the same key bindings as WordStar and its offspring, including DOS and Borland's Turbo languages editors; less is probably the best text browser, and if properly configured lets you browse gzipped, tarred, and zipped files as well; lpr prints a file in background. To check the status of the printing queue, use lpq; to remove a file from the printing queue, use lprm; mc is a great file manager; pine is a nice e-mailing program; script copies to script_file what appears on screen until you issue the command exit. Useful for debugging; sudo allows users to perform some of root's tasks (e.g. formatting and mounting disks; RMP); uname -a gives you info about your system; zcat and zless are useful for viewing gzipped text files without ungzipping them. Possible use: $ zless textfile.gz $ zcat textfile.gz | lpr The following commands often come in handy: bc, cal, chsh, cmp, cut, fmt, head, hexdump, nl, passwd, printf, sort, split, strings, tac, tail, tee, touch, uniq, w, wall, wc, whereis, write, xargs, znew. RMP. 8.5 Extensiones comunes y programas relacionados Puedes hacerte una idea del tipo de fichero por la extension, excluyendo los mas exoticos ( p.e. Tipos de letra, etc.) He aqui una lista de alguno: 1 ... 8: paginas del man. Consige man. arj: archivo creado con arj. unarj para descomprimir. dvi: fichero de salida proporcionado por TeX (ver despues). xdvi para verlo; dvips para pasarlo a fichero postscript .ps. gif: fichero grafico. consige seejpeg o xpaint. gz: archivo creado con gzip. info: fichero de info (pequeña alternativa a las paginas del man). consigue info. jpg, jpeg: fichero grafico. Consigue seejpeg. lsm: Linux Software Map file. Es un fichero de texto ASCII que contiene la descripcion del paquete. ps: fischero postscript. Para verlo consigue gs y opcionalmente ghostview. (Maravilloso!) rpm: Paquete de Red Hat. puedes instalarlo en tu sistema usando el administrador de paquetes rpm. tgz, tar.gz: archivo creado con tar y comprimido con gzip. tex: fichero de texto a entregar a TeX, un potente programa de proceso de texto. Consigue el paquete tex, disponible en muchas distribuciones. Pero cuidado con NTeX, que tiene los tipos de letra coruptos y es distribuido en algunas versiones de Slackware. texi: fichero de texinfo, puede producir ficheros TeX e info (cp. .info). Obten texinfo. xbm, xpm, xwd: ficheros graphicos. Consigue xpaint. zip: archivo creado con zip. consigue zip y unzip. Z: archivo creado con compress. 9. The End, for Now Congratulations! You have now grasped a little bit of UNIX and are ready to start working. Remember that your knowledge of the system is still limited, and that you are expected to do more practice with Linux to use it comfortably. But if all you had to do was get a bunch of applications and start working with them, I bet that what I included here is enough. I'm sure you'll enjoy using Linux and will keep learning more about it---everybody does. I bet, too, that you'll never go back to DOS! I hope I made myself understood and did a good service to my 3 or 4 readers. 9.1 Copyright Unless otherwise stated, Linux HOWTO documents are copyrighted by their respective authors. Linux HOWTO documents may be reproduced and distributed in whole or in part, in any medium physical or electronic, as long as this copyright notice is retained on all copies. Commercial redistribution is allowed and encouraged; however, the author would like to be notified of any such distributions. All translations, derivative works, or aggregate works incorporating any Linux HOWTO documents must be covered under this copyright notice. That is, you may not produce a derivative work from a HOWTO and impose additional restrictions on its distribution. Exceptions to these rules may be granted under certain conditions; please contact the Linux HOWTO coordinator at the address given below. In short, we wish to promote dissemination of this information through as many channels as possible. However, we do wish to retain copyright on the HOWTO documents, and would like to be notified of any plans to redistribute the HOWTOs. If you have questions, please contact Greg Hankins, the Linux HOWTO coordinator, at gregh@sunsite.unc.edu via email. 9.2 Disclaimer ``From DOS to Linux HOWTO'' was written by Guido Gonzato, guido@ibogfs.cineca.it. Many thanks to Matt Welsh, the author of ``Linux Installation and Getting Started'', to Ian Jackson, the author of ``Linux frequently asked questions with answers'', to Giuseppe Zanetti, the author of ``Linux'', to all the folks who emailed me suggestions, and especially to Linus Torvalds and GNU who gave us Linux. This document is provided ``as is''. I put great effort into writing it as accurately as I could, but you use the information contained in it at your own risk. In no event shall I be liable for any damages resulting from the use of this work. Feedback is welcome. For any requests, suggestions, flames, etc., feel free to contact me. Disfruta Linux y la vida, Guido =8-)