BASH Programming − Introduction HOW−TO BASH Programming − Introduction HOW−TO

Total Page:16

File Type:pdf, Size:1020Kb

BASH Programming − Introduction HOW−TO BASH Programming − Introduction HOW−TO BASH Programming − Introduction HOW−TO BASH Programming − Introduction HOW−TO Table of Contents BASH Programming − Introduction HOW−TO.............................................................................................1 by Mike G mikkey at dynamo.com.ar.....................................................................................................1 1.Introduction...........................................................................................................................................1 2.Very simple Scripts...............................................................................................................................1 3.All about redirection.............................................................................................................................1 4.Pipes......................................................................................................................................................1 5.Variables...............................................................................................................................................2 6.Conditionals..........................................................................................................................................2 7.Loops for, while and until.....................................................................................................................2 8.Functions...............................................................................................................................................2 9.User interfaces......................................................................................................................................2 10.Misc....................................................................................................................................................2 11.Tables..................................................................................................................................................3 12.More Scripts........................................................................................................................................3 13.When something goes wrong (debugging).........................................................................................3 14.About the document............................................................................................................................3 1.Introduction...........................................................................................................................................3 1.1 Getting the latest version...................................................................................................................3 1.2 Requisites...........................................................................................................................................4 1.3 Uses of this document........................................................................................................................4 2.Very simple Scripts...............................................................................................................................4 2.1 Traditional hello world script.............................................................................................................4 2.2 A very simple backup script..............................................................................................................4 3.All about redirection.............................................................................................................................5 3.1 Theory and quick reference...............................................................................................................5 3.2 Sample: stdout 2 file .........................................................................................................................5 3.3 Sample: stderr 2 file ..........................................................................................................................5 3.4 Sample: stdout 2 stderr......................................................................................................................6 3.5 Sample: stderr 2 stdout .....................................................................................................................6 3.6 Sample: stderr and stdout 2 file ........................................................................................................6 4.Pipes......................................................................................................................................................6 4.1 What they are and why you'll want to use them................................................................................7 4.2 Sample: simple pipe with sed ...........................................................................................................7 4.3 Sample: an alternative to ls −l *.txt ..................................................................................................7 5.Variables...............................................................................................................................................7 5.1 Sample: Hello World! using variables...............................................................................................7 5.2 Sample: A very simple backup script (little bit better)......................................................................8 5.3 Local variables...................................................................................................................................8 6.Conditionals..........................................................................................................................................9 6.1 Dry Theory.........................................................................................................................................9 6.2 Sample: Basic conditional example if .. then.....................................................................................9 6.3 Sample: Basic conditional example if .. then ... else.......................................................................10 6.4 Sample: Conditionals with variables...............................................................................................10 7.Loops for, while and until...................................................................................................................10 7.1 For sample........................................................................................................................................10 7.2 C−like for.........................................................................................................................................11 7.3 While sample...................................................................................................................................11 i BASH Programming − Introduction HOW−TO Table of Contents 7.4 Until sample.....................................................................................................................................11 8.Functions.............................................................................................................................................12 8.1 Functions sample.............................................................................................................................12 8.2 Functions with parameters sample...................................................................................................12 9.User interfaces....................................................................................................................................13 9.1 Using select to make simple menus.................................................................................................13 9.2 Using the command line .................................................................................................................13 10.Misc..................................................................................................................................................14 10.1 Reading user input with read.........................................................................................................14 10.2 Arithmetic evaluation.....................................................................................................................14 10.3 Finding bash ..................................................................................................................................15 10.4 Getting the return value of a program............................................................................................16 10.5 Capturing a commands output ......................................................................................................16 10.6 Multiple source files......................................................................................................................16 11.Tables................................................................................................................................................16 11.1 String comparison operators..........................................................................................................16 11.2 String comparison examples..........................................................................................................17 11.3 Arithmetic operators......................................................................................................................17
Recommended publications
  • At—At, Batch—Execute Commands at a Later Time
    at—at, batch—execute commands at a later time at [–csm] [–f script] [–qqueue] time [date] [+ increment] at –l [ job...] at –r job... batch at and batch read commands from standard input to be executed at a later time. at allows you to specify when the commands should be executed, while jobs queued with batch will execute when system load level permits. Executes commands read from stdin or a file at some later time. Unless redirected, the output is mailed to the user. Example A.1 1 at 6:30am Dec 12 < program 2 at noon tomorrow < program 3 at 1945 pm August 9 < program 4 at now + 3 hours < program 5 at 8:30am Jan 4 < program 6 at -r 83883555320.a EXPLANATION 1. At 6:30 in the morning on December 12th, start the job. 2. At noon tomorrow start the job. 3. At 7:45 in the evening on August 9th, start the job. 4. In three hours start the job. 5. At 8:30 in the morning of January 4th, start the job. 6. Removes previously scheduled job 83883555320.a. awk—pattern scanning and processing language awk [ –fprogram–file ] [ –Fc ] [ prog ] [ parameters ] [ filename...] awk scans each input filename for lines that match any of a set of patterns specified in prog. Example A.2 1 awk '{print $1, $2}' file 2 awk '/John/{print $3, $4}' file 3 awk -F: '{print $3}' /etc/passwd 4 date | awk '{print $6}' EXPLANATION 1. Prints the first two fields of file where fields are separated by whitespace. 2. Prints fields 3 and 4 if the pattern John is found.
    [Show full text]
  • Administering Unidata on UNIX Platforms
    C:\Program Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\ADMINUNIX\ADMINUNIXTITLE.fm March 5, 2010 1:34 pm Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta UniData Administering UniData on UNIX Platforms UDT-720-ADMU-1 C:\Program Files\Adobe\FrameMaker8\UniData 7.2\7.2rebranded\ADMINUNIX\ADMINUNIXTITLE.fm March 5, 2010 1:34 pm Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Beta Notices Edition Publication date: July, 2008 Book number: UDT-720-ADMU-1 Product version: UniData 7.2 Copyright © Rocket Software, Inc. 1988-2010. All Rights Reserved. Trademarks The following trademarks appear in this publication: Trademark Trademark Owner Rocket Software™ Rocket Software, Inc. Dynamic Connect® Rocket Software, Inc. RedBack® Rocket Software, Inc. SystemBuilder™ Rocket Software, Inc. UniData® Rocket Software, Inc. UniVerse™ Rocket Software, Inc. U2™ Rocket Software, Inc. U2.NET™ Rocket Software, Inc. U2 Web Development Environment™ Rocket Software, Inc. wIntegrate® Rocket Software, Inc. Microsoft® .NET Microsoft Corporation Microsoft® Office Excel®, Outlook®, Word Microsoft Corporation Windows® Microsoft Corporation Windows® 7 Microsoft Corporation Windows Vista® Microsoft Corporation Java™ and all Java-based trademarks and logos Sun Microsystems, Inc. UNIX® X/Open Company Limited ii SB/XA Getting Started The above trademarks are property of the specified companies in the United States, other countries, or both. All other products or services mentioned in this document may be covered by the trademarks, service marks, or product names as designated by the companies who own or market them. License agreement This software and the associated documentation are proprietary and confidential to Rocket Software, Inc., are furnished under license, and may be used and copied only in accordance with the terms of such license and with the inclusion of the copyright notice.
    [Show full text]
  • DC Console Using DC Console Application Design Software
    DC Console Using DC Console Application Design Software DC Console is easy-to-use, application design software developed specifically to work in conjunction with AML’s DC Suite. Create. Distribute. Collect. Every LDX10 handheld computer comes with DC Suite, which includes seven (7) pre-developed applications for common data collection tasks. Now LDX10 users can use DC Console to modify these applications, or create their own from scratch. AML 800.648.4452 Made in USA www.amltd.com Introduction This document briefly covers how to use DC Console and the features and settings. Be sure to read this document in its entirety before attempting to use AML’s DC Console with a DC Suite compatible device. What is the difference between an “App” and a “Suite”? “Apps” are single applications running on the device used to collect and store data. In most cases, multiple apps would be utilized to handle various operations. For example, the ‘Item_Quantity’ app is one of the most widely used apps and the most direct means to take a basic inventory count, it produces a data file showing what items are in stock, the relative quantities, and requires minimal input from the mobile worker(s). Other operations will require additional input, for example, if you also need to know the specific location for each item in inventory, the ‘Item_Lot_Quantity’ app would be a better fit. Apps can be used in a variety of ways and provide the LDX10 the flexibility to handle virtually any data collection operation. “Suite” files are simply collections of individual apps. Suite files allow you to easily manage and edit multiple apps from within a single ‘store-house’ file and provide an effortless means for device deployment.
    [Show full text]
  • The Ifplatform Package
    The ifplatform package Original code by Johannes Große Package by Will Robertson http://github.com/wspr/ifplatform v0.4a∗ 2017/10/13 1 Main features and usage This package provides the three following conditionals to test which operating system is being used to run TEX: \ifwindows \iflinux \ifmacosx \ifcygwin If you only wish to detect \ifwindows, then it does not matter how you load this package. Note then that use of (Linux or Mac OS X or Cygwin) can then be detected with \ifwindows\else. If you also wish to determine the difference between which Unix-variant you are using (i.e., also detect \iflinux, \ifmacosx, and \ifcygwin) then shell escape must be enabled. This is achieved by using the -shell-escape command line option when executing LATEX. If shell escape is not enabled, \iflinux, \ifmacosx, and \ifcygwin will all return false. A warning will be printed in the console output to remind you in this case. ∗Thanks to Ken Brown, Joseph Wright, Zebb Prime, and others for testing this package. 1 2 Auxiliary features \ifshellescape is provided as a conditional to test whether shell escape is active or not. (Note: new versions of pdfTEX allow you to query shell escape with \ifnum\pdfshellescape>0 , and the pdftexcmds package provides the wrapper \pdf@shellescape which works with X TE EX, pdfTEX, and LuaTEX.) Also, the \platformname command is defined to expand to a macro that represents the operating system. Default definitions are (respectively): \windowsname ! ‘Windows’ \notwindowsname ! ‘*NIX’ (when shell escape is disabled) \linuxname ! ‘Linux’ \macosxname ! ‘Mac OS X’ \cygwinname ! ‘Cygwin’ \unknownplatform ! whatever is returned by uname E.g., if \ifwindows is true then \platformname expands to \windowsname, which expands to ‘Windows’.
    [Show full text]
  • Unix Command Line; Editors
    Unix command line; editors Karl Broman Biostatistics & Medical Informatics, UW–Madison kbroman.org github.com/kbroman @kwbroman Course web: kbroman.org/AdvData My goal in this lecture is to convince you that (a) command-line-based tools are the things to focus on, (b) you need to choose a powerful, universal text editor (you’ll use it a lot), (c) you want to be comfortable and skilled with each. For your work to be reproducible, it needs to be code-based; don’t touch that mouse! Windows vs. Mac OSX vs. Linux Remote vs. Not 2 The Windows operating system is not very programmer-friendly. Mac OSX isn’t either, but under the hood, it’s just unix. Don’t touch the mouse! Open a terminal window and start typing. I do most of my work directly on my desktop or laptop. You might prefer to work remotely on a server, instead. But I can’t stand having any lag in looking at graphics. If you use Windows... Consider Git Bash (or Cygwin) or turn on the Windows subsystem for linux 3 Cygwin is an effort to get Unix command-line tools in Windows. Git Bash combines git (for version control) and bash (the unix shell); it’s simpler to deal with than Cygwin. Linux is now accessible in Windows 10, but you have to enable it. If you use a Mac... Consider Homebrew and iTerm2 Also the XCode command line tools 4 Homebrew is a packaging system; iTerm2 is a Terminal replacement. The XCode command line tools are a must for most unixy things on a Mac.
    [Show full text]
  • The Price of Safety: Evaluating IOMMU Performance Preliminary Results
    The Price of Safety: Evaluating IOMMU Performance Preliminary Results Muli Ben-Yehuda [email protected] IBM Haifa Research Lab The Price of Safety: Evaluating IOMMU Performance, 2007 Spring Xen Summit – p.1/14 Table of Contents IOMMUs Preliminary Performance Results Optimizations and Trade-offs Conclusions The Price of Safety: Evaluating IOMMU Performance, 2007 Spring Xen Summit – p.2/14 IOMMUs IOMMU - IO Memory Management Unit Think MMU for IO devices - separate address spaces! IOMMUs enable virtual machines direct hardware access for PV and FV guests ... while protecting the rest of the system from mis-behaving or malicious virtual machines But at what cost? The Price of Safety: Evaluating IOMMU Performance, 2007 Spring Xen Summit – p.3/14 Setting the Stage Full results to appear at OLS ’07 Calgary (PCI-X) and Calgary (PCI-e) IOMMUs Linux and Xen implementations ... with some corroborating evidence from the DART IOMMU on PPC JS21 blades and the IBM Research Hypervisor Joint work with Jimi Xenidis, Michal Ostrowski, Karl Rister, Alexis Bruemmer and Leendert Van Doorn Utilizing IOMMUs for Virtualization in Linux and Xen, by by M. Ben-Yehuda, J. Mason, O. Krieger, J. Xenidis, L. Van Doorn, A. Mallick, J. Nakajima, and E. Wahlig, OLS ’06 The Price of Safety: Evaluating IOMMU Performance, 2007 Spring Xen Summit – p.4/14 On Comparisons What are we comparing against? not emulation not virtual IO (frontend / backend drivers) Direct hardware access without an IOMMU compared with direct hardware access with an IOMMU on the IO path The Price of Safety:
    [Show full text]
  • Geek Guide > Beyond Cron
    GEEK GUIDE BEYOND CRON Table of Contents Ease of Use ..................................................................... 8 Multi-Server-Friendly .................................................... 10 Dependency Management ............................................ 13 Easy to Visualize ........................................................... 16 Delegation of Authority ................................................. 18 Management by Exception ........................................... 21 Flexible Scheduling ....................................................... 23 Revision Control ........................................................... 24 Conclusion .................................................................... 24 MIKE DIEHL has been using Linux since the days when Slackware came on 14 5.25” floppy disks and installed kernel version 0.83. He has built and managed several servers configured with either hardware or software RAID storage under Linux, and he has hands-on experience with both the VMware and KVM virtual machine architectures. Mike has written numerous articles for Linux Journal on a broad range of subjects, and he has a Bachelor’s degree in Mathematics with a minor in Computer Science. He lives in Blythewood, South Carolina, with his wife and four sons. 2 GEEK GUIDE BEYOND CRON GEEK GUIDES: Mission-critical information for the most technical people on the planet. Copyright Statement © 2015 Linux Journal. All rights reserved. This site/publication contains materials that have been created, developed or
    [Show full text]
  • Bash Shell Scripts
    Bash Shell Scripts Writing Bash shell scripts Bash shell scripts are text files Text files most efficiently built with programming editors (emacs or vi) File must be executable and in search path chmod 700 my_script PATH environment variable may not include .! An example shell script: #!/bin/bash #My first script echo "Hello World!" Bash Shell Scripts Writing Bash shell scripts Compile a Verilog file with vlog #!/bin/bash if [ ! d work ] ; then echo work does not exist, making it vlib work fi if [ ! s adder.v ] ; then vlog adder.v fi work directory must exist before compilation Get scripts via wget, eg: wget http://web.engr.oregonstate.edu/~traylor/ece474/script --- Bash Shell Scripts Writing Bash shell scripts File attribute checking #!/bin/bash if [ ! s junk_dir ] ; then mkdir junk_dir fi Spaces around brackets are needed! File attribute checking d exists and is a directory e, a file exists f exists and is a regular file s file exists and is not empty --- Bash Shell Scripts Writing Bash shell scripts Compile Verilog then run a simultion #!/bin/bash if [ ! -d "work" ] ; then vlib work fi if [ -s "adder.v" ] ; then vlog adder.v #runs simulation with a do file and no GUI vsim adder -do do.do quiet c else echo verilog file missing fi --- Bash Shell Scripts Writing Bash shell scripts vsim command and arguments vsim entity_name do dofile.do quiet -c -quiet (do not report loading file messages) -c (console mode, no GUI) -do (run vsim from a TCL do file) +nowarnTFMPC (don’t warn about mismatched ports, scary) +nowarnTSCALE (don’t warn about timing mismatches) Try vsim help for command line arguements --- Bash Shell Scripts Writing Bash Shell Scripts (TCL Script) In another text file, we create a TCL script with commands for the simulator.
    [Show full text]
  • Tcl/Tk for Xspecta Michael Flynn Tcl: Tcl (Ie Tool Command Language)
    Tcl/Tk for XSPECTa Michael Flynn Tcl: Tcl (i.e. Tool Command Language) is an open source scripting language similar to other modern script languages such as Perl or Python. It is substantially more powerful than UNIX/LINUX/POSIX shell script languages such as the Bourne Shell (sh), the C Shell (csh), or the Korn Shell (https://en.wikipedia.org/wiki/Shell_script). Tcl and its associated graphical user interface toolkit, Tk, were developed by John Ousterhout of the University of California. Ousterhout's group subsequently continued development of Tcl/Tk while at Sun Microsystems and later at Scriptics. Continued development is now done by an open source project team. The language has been popular for developing graphic applications and is available as public domain software for almost all computer systems (Linux, Windows and MacOS). Installation: Tcl/Tk software can be found at: http://www.activestate.com/activeTcl Binary Windows installers are available from this site for both 32 and 64 bit systems as a Free Community Edition. The lab modules were last validated with Version 8.6.4.1 but more recent versions should not be problematic. Unless Tcl has already been installed on the system being used, download and install the software from ActiveState. The installer should be run with administrative privileges. On Windows7, you should right click and 'run as administrator'. Installing with elevated privilege will allow the registry changes that map Tcl extensions and will configure the un-installer database, making later removal of ActiveTcl easier. The ActiveState default installation directory is C:/Tcl. During the installation, the installer will ask if you want this changed.
    [Show full text]
  • A First Course to Openfoam
    Basic Shell Scripting Slides from Wei Feinstein HPC User Services LSU HPC & LON [email protected] September 2018 Outline • Introduction to Linux Shell • Shell Scripting Basics • Variables/Special Characters • Arithmetic Operations • Arrays • Beyond Basic Shell Scripting – Flow Control – Functions • Advanced Text Processing Commands (grep, sed, awk) Basic Shell Scripting 2 Linux System Architecture Basic Shell Scripting 3 Linux Shell What is a Shell ▪ An application running on top of the kernel and provides a command line interface to the system ▪ Process user’s commands, gather input from user and execute programs ▪ Types of shell with varied features o sh o csh o ksh o bash o tcsh Basic Shell Scripting 4 Shell Comparison Software sh csh ksh bash tcsh Programming language y y y y y Shell variables y y y y y Command alias n y y y y Command history n y y y y Filename autocompletion n y* y* y y Command line editing n n y* y y Job control n y y y y *: not by default http://www.cis.rit.edu/class/simg211/unixintro/Shell.html Basic Shell Scripting 5 What can you do with a shell? ▪ Check the current shell ▪ echo $SHELL ▪ List available shells on the system ▪ cat /etc/shells ▪ Change to another shell ▪ csh ▪ Date ▪ date ▪ wget: get online files ▪ wget https://ftp.gnu.org/gnu/gcc/gcc-7.1.0/gcc-7.1.0.tar.gz ▪ Compile and run applications ▪ gcc hello.c –o hello ▪ ./hello ▪ What we need to learn today? o Automation of an entire script of commands! o Use the shell script to run jobs – Write job scripts Basic Shell Scripting 6 Shell Scripting ▪ Script: a program written for a software environment to automate execution of tasks ▪ A series of shell commands put together in a file ▪ When the script is executed, those commands will be executed one line at a time automatically ▪ Shell script is interpreted, not compiled.
    [Show full text]
  • Introduction to Cron - Goals
    Introduction to cron - Goals • Goals: – Understand how cron works – Understand crontab files – Understand our conventions 1 What is cron? • cron is a Unix daemon program • cron automatically runs programs at given times • cron is different from at, which is a queued batch job facility • We are moving to use cron for batch jobs, as opposed to at 2 Crontab files (Part 1) • Each user on each machine has a crontab file. • So, ecogdev has its own file on each of sid & soltrane, as does ecogdba. • This file consists of lines that look like this: 15 03 * * * /ecog/ecogdev/src/reports/timezone/timezoneauto 15 03 * * 0 /ecog/ecogdev/src/reports/swog_prots/swog_protsauto 30 0 * * * /ecog/ecogdev/bin/ftpschema 3 Crontab Files (Part 2) • Here is one line from a crontab file: 30 0 * * * /ecog/ecogdev/bin/ftpschema • Six fields on this line (* is a wildcard): – 1. Minute of the hour (0-59) – 2. Hour of the day (0-23) – 3. Day of the month (0-31) – 4. Month of the year (1-12) – 5. Day of the week (0-6 with 0=Sunday) – 6. Command line • Quiz: When does this job run? 4 Crontab Files (Part 3) • Here is that crontab line again: 30 0 * * * /ecog/ecogdev/bin/ftpschema • The rightmost field is the command line • Best to use absolute paths, as in this entry • Commands can be executable programs or shell scripts • Put #!/bin/csh at top of C Shell scripts 5 The crontab command • The crontab command allows you to install and edit per-user crontab files. • These are the installed crontab files.
    [Show full text]
  • Unix/Linux Command Reference
    Unix/Linux Command Reference .com File Commands System Info ls – directory listing date – show the current date and time ls -al – formatted listing with hidden files cal – show this month's calendar cd dir - change directory to dir uptime – show current uptime cd – change to home w – display who is online pwd – show current directory whoami – who you are logged in as mkdir dir – create a directory dir finger user – display information about user rm file – delete file uname -a – show kernel information rm -r dir – delete directory dir cat /proc/cpuinfo – cpu information rm -f file – force remove file cat /proc/meminfo – memory information rm -rf dir – force remove directory dir * man command – show the manual for command cp file1 file2 – copy file1 to file2 df – show disk usage cp -r dir1 dir2 – copy dir1 to dir2; create dir2 if it du – show directory space usage doesn't exist free – show memory and swap usage mv file1 file2 – rename or move file1 to file2 whereis app – show possible locations of app if file2 is an existing directory, moves file1 into which app – show which app will be run by default directory file2 ln -s file link – create symbolic link link to file Compression touch file – create or update file tar cf file.tar files – create a tar named cat > file – places standard input into file file.tar containing files more file – output the contents of file tar xf file.tar – extract the files from file.tar head file – output the first 10 lines of file tar czf file.tar.gz files – create a tar with tail file – output the last 10 lines
    [Show full text]