La Kornshell: Lenguaje De Programación Y Comando

Total Page:16

File Type:pdf, Size:1020Kb

La Kornshell: Lenguaje De Programación Y Comando La KornShell: Lenguaje de Programación y Comando Una guía para programadores de Shell Scripts de Unix Jesús Alberto Vidal Cortés http://inicia.es/de/chube [email protected] www.kornshell.com Madrid, Agosto de 2001 Índice PARTE I: INTRODUCCIÓN......................................................................................................... 11 1. SOBRE EL LENGUAJE KORNSHELL ........................................................................................... 12 ¿Qué es una Shell?.............................................................................................................. 12 Beneficios del uso de ksh..................................................................................................... 13 Mejoras como Lenguaje de Comandos ................................................................................................................ 13 Mejoras como Lenguaje de Programación........................................................................................................... 14 Versiones a las que se aplica este manual............................................................................. 15 ¿Cómo obtener ksh?............................................................................................................ 16 2. NOTACIÓN UTILIZADA EN ESTE MANUAL..................................................................................... 18 General ............................................................................................................................... 18 Teclas sobre el Terminal....................................................................................................... 18 Nombres simbólicos para Constantes.................................................................................... 18 Notación de sintaxis de comandos ........................................................................................ 19 PARTE II: TUTORIAL ................................................................................................................. 20 3. CONCEPTOS DEL SISTEMA OPERATIVO...................................................................................... 21 Ficheros .............................................................................................................................. 21 Convenciones de nomenclatura............................................................................................................................. 21 Permisos de Ficheros .............................................................................................................................................. 23 Ficheros y Directorios Especiales .......................................................................................................................... 23 Procesos ............................................................................................................................. 24 Creando y Destruyendo Procesos ......................................................................................................................... 24 Relaciones entre Procesos ..................................................................................................................................... 25 Permisos de Procesos ............................................................................................................................................. 25 Señales ....................................................................................................................................................................... 26 Comunicación entre Procesos ................................................................................................................................ 27 Entorno del Proceso................................................................................................................................................. 27 Descriptores de Fichero........................................................................................................................................... 28 Cadenas y Patrones ............................................................................................................. 28 Caracteres y Cadenas ............................................................................................................................................. 28 Ordenación por Comparación de Cadenas .......................................................................................................... 29 Patrones ..................................................................................................................................................................... 29 4. LENGUAJE DE COMANDOS ...................................................................................................... 31 Ejecución de comandos simples ........................................................................................... 31 Fijando y visualizando las opciones ....................................................................................... 33 Corrigiendo lo tecleado......................................................................................................... 34 Utilizando el “alias” como abreviatura .................................................................................... 35 Reintroduciendo comandos previos ....................................................................................... 35 Cambiando el permiso de los ficheros ................................................................................... 36 Redireccionando la entrada y la salida................................................................................... 38 - 2 - Pipelines (encauzamiento) y Filtros ....................................................................................... 39 Expansión de la Tilde........................................................................................................... 40 Variables ............................................................................................................................. 41 Expansión del “Pathname”.................................................................................................... 41 Comandos de Timing ........................................................................................................... 42 Entrecomillando caracteres especiales .................................................................................. 43 Directorio de trabajo ............................................................................................................. 44 Como encuentra ksh un comando ......................................................................................... 44 Substitución de comandos .................................................................................................... 45 Ejecución de comandos en modo desatendido....................................................................... 46 Control de Jobs o Trabajos ................................................................................................... 47 Comandos Compuestos ....................................................................................................... 49 Shell Scripts ........................................................................................................................ 49 5. LENGUAJE DE PROGRAMACIÓN................................................................................................ 51 Introducción a los Parámetros............................................................................................... 51 Parámetros Posicionales ...................................................................................................... 51 Más sobre los Parámetros .................................................................................................... 53 Valores de retorno................................................................................................................ 54 Más sobre entrecomillado..................................................................................................... 55 Matching o “encaje” con patrones.......................................................................................... 56 Abriendo y cerrando ficheros ................................................................................................ 57 Leyendo de Terminales y ficheros ......................................................................................... 58 Escribiendo a terminales y ficheros ....................................................................................... 59 Here-Documents (documentos empotrados).......................................................................... 60 Co-Procesos ........................................................................................................................ 60 Agrupación de comandos ..................................................................................................... 61 Aritmética............................................................................................................................ 62 Chequeando ficheros y cadenas ........................................................................................... 63 Comandos compuestos ........................................................................................................ 64 Arrays ................................................................................................................................
Recommended publications
  • Squeezing Water from Stone: Kornshell in 2019
    Squeezing Water from Stone: KornShell in 2019 Siteshwar Vashisht @SiteshwarV main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);} ● Winner of IOCCC (The International Obfuscated C Code Contest) one line entry in 1987. ● Termed as best one liner ever received. ● Written by David Korn. What this talk is about ? ● It’s about AT&T KornShell (ksh, not mksh or pdksh). ● Brief status update from new upstream maintainers (Kurtis Rader and Siteshwar Vashisht). ● No deep dive in the source code. ● It is slightly extended version of my talk from FOSDEM 2019 and All Systems Go! 2019. /whois situ ● Siteshwar Vashisht. ● Based in Brno, Czech Republic. ● Maintainer of bash and ksh at Red Hat. ● Previously involved with fish shell and Sailfish OS. ● Current upstream maintainer of ksh. What is KornShell ? ● Direct descendant of Bourne shell. ● Initial development based on original bourne shell. ● Roots back to late 70’s and early 80’s. Spot the bug! #!/bin/bash echo $'hello world' | while read foo do bar="$foo" done echo "bar: " "$bar" $bar is not available outside loop. Bash forks last command in a new process and $bar is lost. Advantages ● Superior language specification (Support for Discipline functions, namespaces, compound data type, enums etc.). ● Better POSIX compliance. ● Fastest POSIX shell. Show me the numbers! $ cat test.sh for ((i=0;i<10000;i++)) do foo=$(echo "bar baz") done $ time bash test.sh $ time zsh test.sh $ time ksh test.sh real 0m2.977s real 0m2.433s real 0m0.078s user 0m2.032s user 0m1.570s user 0m0.062s sys 0m1.167s sys 0m1.233s sys 0m0.015s A 20 year old bug State of ksh in 2017 ● Previous developers have left.
    [Show full text]
  • Common Desktop Environment: Desktop Kornshell User's Guide
    Common Desktop Environment: Desktop KornShell User’s Guide Sun Microsystems, Inc. 901 San Antonio Road Palo Alto, CA 94303 U.S.A. Part No: 805-3917–10 October 1998 Copyright 1998 Sun Microsystems, Inc. 901 San Antonio Road, Palo Alto, California 94303-4900 U.S.A. All rights reserved. This product or document is protected by copyright and distributed under licenses restricting its use, copying, distribution, and decompilation. No part of this product or document may be reproduced in any form by any means without prior written authorization of Sun and its licensors, if any. Third-party software, including font technology, is copyrighted and licensed from Sun suppliers. Parts of the product may be derived from Berkeley BSD systems, licensed from the University of California. UNIX is a registered trademark in the U.S. and other countries, exclusively licensed through X/Open Company, Ltd. Sun, Sun Microsystems, the Sun logo, SunDocs, Java, the Java Coffee Cup logo, and Solaris are trademarks, registered trademarks, or service marks of Sun Microsystems, Inc. in the U.S. and other countries. All SPARC trademarks are used under license and are trademarks or registered trademarks of SPARC International, Inc. in the U.S. and other countries. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc. The OPEN LOOK and SunTM Graphical User Interface was developed by Sun Microsystems, Inc. for its users and licensees. Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical user interfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, which license also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written license agreements.
    [Show full text]
  • Squeezing Water from Stone: Kornshell in 2019
    Squeezing Water from Stone: KornShell in 2019 Siteshwar Vashisht @SiteshwarV main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);} ● Winner of IOCCC (The International Obfuscated C Code Contest) one line entry in 1987. ● Termed as best one liner ever received. ● Written by David Korn. What this talk is about ? ● It’s about AT&T KornShell (ksh, not mksh or pdksh). ● Brief status update from new upstream maintainers (Kurtis Rader and Siteshwar Vashisht). ● No deep dive in the source code. ● It is slightly extended version of my talk from FOSDEM 2019. /whois situ ● Siteshwar Vashisht. ● Based in Brno, Czech Republic. ● Maintainer of bash and ksh at Red Hat. ● Previously involved with fish shell and Sailfish OS. ● Current upstream maintainer of ksh. What is KornShell ? ● Direct descendant of Bourne shell. ● Initial development based on original bourne shell. ● Roots back to late 70’s and early 80’s. Spot the bug! #!/bin/bash echo $'hello world' | while read foo do bar="$foo" done echo "bar: " "$bar" $bar is not available outside loop. Bash forks last command in a new process and $bar is lost. Advantages ● Superior language specification (Support for Discipline functions, namespaces, compound data type, enums etc.). ● Better POSIX compliance. ● Fastest POSIX shell. Show me the numbers! $ cat test.sh for ((i=0;i<10000;i++)) do foo=$(echo "bar baz") done $ time bash test.sh $ time zsh test.sh $ time ksh test.sh real 0m2.977s real 0m2.433s real 0m0.078s user 0m2.032s user 0m1.570s user 0m0.062s sys 0m1.167s sys 0m1.233s sys 0m0.015s A 20 year old bug State of ksh in 2017 ● Previous developers have left.
    [Show full text]
  • Squeezing Water from Stone: Kornshell in 2019
    Squeezing Water from Stone: KornShell in 2019 main() { printf(&unix["\021%six\012\0"],(unix)["have"]+"fun"-0x60);} ●Winner of IOCCC (The International Obfuscated C Code Contest) one line entry in 1987. ●Termed as best one liner ever received. ●Written by David Korn. What this talk is about ? ●It’s about AT&T KornShell (and not mksh/pdksh). ●Brief status update from new upstream maintainers (Kurtis Rader and Siteshwar Vashisht). ●No deep dive in the source code. /whois situ ●Siteshwar Vashisht. ●Based in Brno, Czech Republic. ●Maintainer of bash and ksh at Red Hat. ●Previously involved with fish shell and Sailfish OS. ●Current upstream maintainer of ksh. What is KornShell ? ●Direct descendant of Bourne shell. ●Initial development based on original bourne shell. ●Roots back to late 70s/early 80s. Advantages ●Superior language specification (Support for Discipline functions, namespaces, compound data type, enums etc.). ●Better POSIX compliance. ●Fastest POSIX shell. A 20 year old bug State of ksh in 2017 ●Previous developers have left. ●Codebase has origins going back to the 80s. ●Old Tooling. ●No revision control history. ●Almost no comments in the source code. ●Spaghetti code. ●Bad test coverage. ●Lots of old bugs. ●And ... How to maintain the unmaintainable ? One of my most productive days was throwing away 1,000 lines of code - Ken Thompson We threw away more than 500,000 lines of code. Lines of code (ksh93v-) Lines of code (current) What did we drop ? ●Support for non-POSIX operating systems. ●Reimplementation of POSIX functions. ●Entire subsystems like the AST vmalloc and locale. ●Lots of code that was not used by ksh.
    [Show full text]
  • Mastering EOS Release 1.0
    Mastering EOS Release 1.0 Sean Fisk and Ira Woodring May 12, 2015 CONTENTS 1 Introduction 3 1.1 Physical Access (Keycards) ....................................... 3 1.2 Computer Access (Credentials) ..................................... 3 2 Rules and Procedures 5 2.1 Disk Space ................................................ 5 2.2 Copyrighted Material ........................................... 5 2.3 Food and Drink .............................................. 6 2.4 Overnight Parking ............................................ 6 2.5 Living in the Lab ............................................. 6 2.6 Malicious Activity ............................................ 6 2.7 Games .................................................. 6 3 Using the Command Line 7 3.1 Command-Line Basics .......................................... 7 3.2 Available Shells ............................................. 7 3.3 Interactive Shell Use ........................................... 10 3.4 Shell Scripting .............................................. 24 4 Remote Access (SSH/VNC) 27 4.1 Inter-EOS SSH .............................................. 27 4.2 Microsoft Windows ........................................... 28 4.3 Mac OS X ................................................ 36 4.4 GNU/Linux ................................................ 49 5 User-level Software Installation 65 5.1 The Standard Hierarchy ......................................... 65 5.2 Manual Installation ............................................ 66 5.3 Linuxbrew ...............................................
    [Show full text]
  • All MKS Toolkit Commands
    All MKS Toolkit Commands The various MKS Toolkit products include different subsets of commands and utilities. Click the product link on the right to view the product-specific command lists. * denotes a Shell built-in † denotes a groff command ‡ denotes a command which requires an X Server § denotes a command that applies only to N uTCRACKER Platform applications ¥ denotes a command whose binary and source code can be found in the Samples directory of the CD distribution or in the Resource Kit and is an example of porting UNIX source code with MKS Toolkit for Enterprise Developers . * — execute KornShell script in current environment : * — expand arguments and do nothing, successfully [ * — test for condition [[ * — test for condition 64decode.exe — decode a file using base64 64encode.exe — encode a file using base64 a2p.exe — awk to perl translator addftinfo.exe †¥ — add information to troff font files for use with groff afmtodit.exe †¥ — create font files fo ruse with groff -Tps alias * — display or create command aliases appc.ksh — arbitrary precision programmable calculator AppPkgWz.exe — Packaging Wizard for deploying MKS Toolkit ported applications. appres.exe ‡ — list X application resource database ar.exe — create and maintain library archives asa.exe — interpret ASA/FORTRAN carriage control assoc.ksh — set file extension association at.exe — execute commands at a later time atobm.exe ‡ — bitmap editor and converter for the X Window System autoload * — display or modify Shell functions autorun.ksh — specify programs to run on bootup
    [Show full text]
  • Korn-Shell-Programmierung Und Zeichenkettenverarbeitung Unter Unix/Linux
    Korn-Shell-Programmierung und Zeichenkettenverarbeitung unter Unix/Linux FWPF WS 2005/2006 -- Februar 02.2006 © Th. Fuhr Korn-Shell-Programmierung und Zeichenkettenverarbeitung 1 unter Unix/Linux Überblick • Einstieg Korn-Shell – Konfiguration, History-Funktion, Kommandozeilen-Editing – Kommandos und Kommandoverknüpfung – Kommandosubstitution – Reguläre Ausdrücke – Dateinamenexpansion – Quoting – Debugging • Unix-Tools (Teil 1) – Auflistung von Dateinamen – Ausgabe von Zeilen genannter Dateien – Ausgabe von manipulierten Zeileninhalten genannter Dateien • Korn-Shell (Fortsetzung) 02.2006 © Th. Fuhr Korn-Shell-Programmierung und Zeichenkettenverarbeitung 2 unter Unix/Linux Überblick • Korn-Shell-Skripten – Skriptform & -aufruf – Skript I/O: print – Shellvariablen (Grundlagen), Parametersubstitution, Quoting – Datenübergabe – Datenrückgabe – Variablenmanipulation – Bedingte Verzweigung & Bedingungstest – Schleifen – Arrays & Positionsparameter – Variablenattribute – Ein-Ausgabe-Umlenkung – Benutzermenues – Optionsverarbeitung – Funktionen – zweifache Kommandozeilenverarbeitung – Zeitmessung 02.2006 © Th. Fuhr Korn-Shell-Programmierung und Zeichenkettenverarbeitung 3 unter Unix/Linux Überblick • Unix-Tools (Teil 2) – fgrep, grep, egrep – sed 02.2006 © Th. Fuhr Korn-Shell-Programmierung und Zeichenkettenverarbeitung 4 unter Unix/Linux Literatur • Linux-Unix-Shells ksh (sh, bash, csh, tcsh) Helmut Herold Bsp. als tgz-File-Download Addison-Wesley, 1999 • Linux-Unix-Kurzreferenz ksh (sh, bash, csh, tcsh) Helmut Herold Unix/Linux-Tools Addison-Wesley,
    [Show full text]
  • MKS Toolkit for Developers
    MKS Toolkit for Developers A mixed computing environment, . Efficiently and cost-effectively Issues of interoperability also by consequence, demands a deploy UNIX trained affect development for the Web, consistent set of commands and personnel to new platforms. as companies intermingle UNIX utilities. A significant number of and Windows Web servers. MKS . Ease the interoperability corporate developers are fluent in Toolkit for Developers has high- challenge by seamlessly the UNIX environment, so utilities performance text utilities and sharing programming scripts, which are UNIX-based yet specialized Web development files and data between UNIX operate in Windows, can instantly tools that are ideal for and Windows. leverage the skills of UNIX trained maintaining HTML and all aspects people onto new platforms. of Web sites. Scripting languages and familiar MKS Toolkit for Developers also tools ensure that the valuable accelerates personal performance Lower TCO through Enterprise programming expertise of UNIX on the Windows platform by Interoperability developers, and the power of including Windows specific tools Instead of choosing between commands such as the KornShell, to: Windows and UNIX, most MIS CShell, awk, and Perl, does not . Unify and automate software organizations are opting for a mix have to be compromised because builds across UNIX and of the two operating systems, of the introduction of Windows. Windows. with many larger organizations Such utilities also reduce the using Windows as an add-on to immediate need for cross- . Connect to remote UNIX and their enterprise-wide backroom platform training. Windows machines. strategy. In order to decrease the total cost of ownership (TCO) of Global 2000 customers use the .
    [Show full text]
  • Unix Scripts and Job Scheduling Overview Running a Shell Script
    Unix Scripts and Job Scheduling Michael B. Spring Department of Information Science and Telecommunications University of Pittsburgh [email protected] http://www.sis.pitt.edu/~spring Overview Ü Shell Scripts Shell script basics Variables in shell scripts Kornshell arithmetic Commands for scripts Flow control, tests, and expressions Making Scripts Friendlier Functions Pipes and Shell Scripts Scripts with awk and/or sed Ü Job Scheduling bg and at cron Running a Shell Script Ü First three forms spawn a new process, so new variable values are not left when you return sh < filename – wheresh is the name of a shell – does not allow arguments sh filename filename – Assumes directory in path – Assumeschmod +x filename . filename – Does not spawn a new shell. – Changes to system variables impact the current shell Ü you may exit a shell script by Getting to the last line Encountering an exit command Executing a command that results in an error condition that causes an exit. 1 Structure of a Shell Script Ü Basic structure #! Program to execute script # comment Commands and structures Ü Line continuation | at the end of the line is an assumed continuation \ at the end of a line is an explicit continuation Ü # in a shell script indicates a comment to \n Ü Back quotes in command cause immediate execution and substitution Debugging a script Ü Use the command set –x within a script Ü You can also activate the following set options -n read commands before executing them – for testing scripts -u make it an error to reference a non existing file -v print input as it is read - disable the –x and –v commands Ü Set the variable PS4 to some value that will help – e.g.
    [Show full text]
  • Section 2 LINUX.Pdf
    WINDOWS AND LINUX LAB SECTION 2 LINUX Structure Page Nos. 2.0 Introduction 14 2.1 Objectives 14 2.2 History of UNIX and LINUX 15 2.3 Features of LINUX 16 2.4 Kernel and the Shell 17 2.4.1 Commands and Processes 2.4.2 LINUX File System 2.4.3 Wild Card Characters 2.4.4 Syntax of LINUX Commands 2.4.5 Getting Help 2.5 LINUX Commands 22 2.6 Description of Commonly Used LINUX Commands 26 2.7 Introduction to Shell Programming 34 2.7.1 LINUX Shells 2.7.2 Deciding on a Shell 2.8 Bourne Again Shell Programming 36 2.9 General Guidelines 42 2.10 Practical Sessions 44 2.11 Summary 48 2.12 Further Readings 48 2.13 Website References 48 2.14 Virtual Labs / IDEs / Online Lab Resources 49 2.0 INTRODUCTION This is the lab course, wherein you will have the hands on experience. You have studied the course material (MCS-203 Operating Systems). A list of tasks to be performed (sessionwise) on LINUX is given along with some programming problems towards the end. Please go through the general guidelines and the program documentation guidelines carefully. 2.1 OBJECTIVES After completing this lab course you will be able to: Apply the concepts that have been covered in the theory course; Understand the features LINUX; Gain experience in overall command line interface as well as GUI; Make use of different functions/operations of LINUX; Work with the utilities in LINUX; Write simple shell programs and simulate the functionalities for the given tasks; To understand and make effective use Shell scripting language Bash to solve Problems.
    [Show full text]
  • User Commands Ksh ( 1 ) Ksh, Rksh – Kornshell, a Standard/Restricted
    User Commands ksh ( 1 ) NAME ksh, rksh ± KornShell, a standard/restricted command and programming language SYNOPSIS /usr/bin/ksh [ ± abCefhikmnoprstuvx ] [ ± o option ] ... [ arg ... ] /usr/bin/ksh -c [ ± abCefhikmnoprstuvx ] [ ± o option ] ... command_string [ command_name [ arg ... ] ] /usr/xpg4/bin/sh [ ± abCefhikmnoprstuvx ] [ ± o option ] ... [ arg ... ] /usr/xpg4/bin/sh -c [ ± abCefhikmnoprstuvx ] [ ± o option ] ... command_string [ command_name [ arg ... ] ] /usr/bin/rksh [ ± abCefhikmnoprstuvx ] [ ± o option ] ... [ arg ... ] /usr/bin/rksh -c [ ± abCefhikmnoprstuvx ] [ ± o option ] ... command_string [ command_name [ arg ... ] ] DESCRIPTION /usr/xpg4/bin/sh is identical to /usr/bin/ksh, a command and programming language that executes com- mands read from a terminal or a ®le. rksh is a restricted version of the command interpreter ksh; it is used to set up login names and execution environments whose capabilities are more controlled than those of the standard shell. See Invocation below for the meaning of arguments to the shell. De®nitions A metacharacter is one of the following characters: ; & ( ) < > NEWLINE SPACE TAB A blank is a TAB or a SPACE. An identi®er is a sequence of letters, digits, or underscores starting with a letter or underscore. Identi®ers are used as names for functions and variables. A word is a sequence of characters separated by one or more non-quoted metacharacters. A command is a sequence of characters in the syntax of the shell language. The shell reads each com- mand and carries out the desired action either directly or by invoking separate utilities. A special- command is a command that is carried out by the shell without creating a separate process. Except for documented side effects, most special commands can be implemented as separate utilities.
    [Show full text]
  • GUIDE Du Kornshell Sous UNIX
    GUIDE du KornShell sous UNIX (HP-UX 8.0, SUNOS 5.1, AIX 3.2) jh Soulier Jean François Pujol août 93 ✆jf pujol, 18 août 1993 page 2 - Guide du KornShell sous UNIX INTRODUCTION Ce document constitue une aide à la programmation du KornShell (ksh), et non un manuel de référence; c’est pourquoi il est destiné aux utilisateurs ayant déjà des connaissances de base d’un shell (sh ou csh). Il contient des exemples qui se veulent instructifs, et pas une base rigide de programmation : vous y piocherez donc ce qui vous semble bon. Tous les exemples ont été exécutés à l’origine sur un hp9000 série 400, sous HP-UX 8.0, avec une version du KornShell datée du 16/11/88. La version HP-UX 9.0 n’a apporté que de légères modifications au niveau des commandes (convergence vers POSIX 1003.2), mais n’a pas été testée ici spécifiquement. Dans le cas où une incompatibilité apparaîtrait, le mieux est de se référer aux spécificités SUN ou IBM: il est probable que l’une d’entre elles permette de comprendre le phénomène. Il faut savoir que HP fournit le shell POSIX (appelé sh, comme le BourneShell) à partir de la version 9.0, et que le shell POSIX est presque une copie conforme du KornShell. Pour tenir compte des utilisateurs travaillant sous SUN-OS 5.X (SOLARIS 2.X), ou AIX 3.2, les exemples ont été testés également dans ces environnements, et les différences qui apparaissent par rapport à la version HP-UX figurent en annexe.
    [Show full text]