sottotitolo A.A. 2016/17 Federico Reghenzani, Alessandro Barenghi

Similar documents
Introduction Variables Helper commands Control Flow Constructs Basic Plumbing. Bash Scripting. Alessandro Barenghi

Shell. SSE2034: System Software Experiment 3, Fall 2018, Jinkyu Jeong

Useful Unix Commands Cheat Sheet

Shells & Shell Programming (Part B)

Essentials for Scientific Computing: Bash Shell Scripting Day 3

Table of contents. Our goal. Notes. Notes. Notes. Summer June 29, Our goal is to see how we can use Unix as a tool for developing programs

EECS2301. Example. Testing 3/22/2017. Linux/Unix Part 3. for SCRIPT in /path/to/scripts/dir/* do if [ -f $SCRIPT -a -x $SCRIPT ] then $SCRIPT fi done

Shell Programming Systems Skills in C and Unix

Command Interpreters. command-line (e.g. Unix shell) On Unix/Linux, bash has become defacto standard shell.

Answers to AWK problems. Shell-Programming. Future: Using loops to automate tasks. Download and Install: Python (Windows only.) R

BASH and command line utilities Variables Conditional Commands Loop Commands BASH scripts

Bash scripting Tutorial. Hello World Bash Shell Script. Super User Programming & Scripting 22 March 2013

INTRODUCTION TO SHELL SCRIPTING ITPART 2

Shells and Shell Programming

EECS 470 Lab 5. Linux Shell Scripting. Friday, 1 st February, 2018

UNIX Shell Programming

Week Overview. Simple filter commands: head, tail, cut, sort, tr, wc grep utility stdin, stdout, stderr Redirection and piping /dev/null file

Shell Programming. Introduction to Linux. Peter Ruprecht Research CU Boulder

Basic Linux (Bash) Commands

CS 25200: Systems Programming. Lecture 11: *nix Commands and Shell Internals

Linux shell programming for Raspberry Pi Users - 2

UNIX System Programming Lecture 3: BASH Programming

Shells and Shell Programming

bash, part 3 Chris GauthierDickey

Shell Scripting. With Applications to HPC. Edmund Sumbar Copyright 2007 University of Alberta. All rights reserved

While Statement Examples. While Statement (35.15) Until Statement (35.15) Until Statement Example

bash Args, Signals, Functions Administrative Shell Scripting COMP2101 Fall 2017

Processes. Shell Commands. a Command Line Interface accepts typed (textual) inputs and provides textual outputs. Synonyms:

1. Hello World Bash Shell Script. Last Updated on Wednesday, 13 April :03

Last Time. on the website

Processes and Shells

More Scripting Techniques Scripting Process Example Script

Shell scripting and system variables. HORT Lecture 5 Instructor: Kranthi Varala

Basics. I think that the later is better.

Bourne Shell Reference

Review of Fundamentals

CS Unix Tools & Scripting

Common File System Commands

CS 307: UNIX PROGRAMMING ENVIRONMENT KATAS FOR EXAM 2

Part III. Shell Config. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Review of Fundamentals. Todd Kelley CST8207 Todd Kelley 1

More Scripting and Regular Expressions. Todd Kelley CST8207 Todd Kelley 1

Lecture 5. Essential skills for bioinformatics: Unix/Linux

Chapter 4. Unix Tutorial. Unix Shell

Bash Shell Programming Helps

Module 8 Pipes, Redirection and REGEX

Why Bourne Shell? A Bourne Shell Script. The UNIX Shell. Ken Wong Washington University. The Bourne Shell (CSE 422S)

5/8/2012. Exploring Utilities Chapter 5

Linux shell scripting Getting started *

Scripting. More Shell Scripts Loops. Adapted from Practical Unix and Programming Hunter College

Chapter 9. Shell and Kernel

Introduction: What is Unix?

Windshield. Language Reference Manual. Columbia University COMS W4115 Programming Languages and Translators Spring Prof. Stephen A.

CS 25200: Systems Programming. Lecture 10: Shell Scripting in Bash

Topic 2: More Shell Skills

Bash command shell language interpreter

Output with printf Input. from a file from a command arguments from the command read

Vi & Shell Scripting

Process Management! Goals of this Lecture!

I/O and Shell Scripting

Shell Programming (bash)

Topic 2: More Shell Skills. Sub-Topic 1: Quoting. Sub-Topic 2: Shell Variables. Difference Between Single & Double Quotes

Shell programming. Introduction to Operating Systems

Part 1: Basic Commands/U3li3es

Lab 2: Linux/Unix shell

Unix as a Platform Exercises + Solutions. Course Code: OS 01 UNXPLAT

A shell can be used in one of two ways:

Advanced Linux Commands & Shell Scripting

BASH SHELL SCRIPT 1- Introduction to Shell

STATS Data Analysis using Python. Lecture 15: Advanced Command Line

CSE 15L Winter Midterm :) Review

CSE 390a Lecture 2. Exploring Shell Commands, Streams, and Redirection

Mills HPC Tutorial Series. Linux Basics II

More Scripting Todd Kelley CST8207 Todd Kelley 1

Introduction to Linux Basics Part II. Georgia Advanced Computing Resource Center University of Georgia Suchitra Pakala

Introduction to the Shell

Shell Scripting. Todd Kelley CST8207 Todd Kelley 1

Today. Review. Unix as an OS case study Intro to Shell Scripting. What is an Operating System? What are its goals? How do we evaluate it?

Topic 2: More Shell Skills

COMP 4/6262: Programming UNIX

Consider the following program.

Chapter 1 - Introduction. September 8, 2016

Perl. Many of these conflict with design principles of languages for teaching.

Process Management 1

CS246 Spring14 Programming Paradigm Files, Pipes and Redirection

Basic UNIX Commands BASIC UNIX COMMANDS. 1. cat command. This command is used to create a file in unix. Syntax: $ cat filename

Lecture 4. Log into Linux Reminder: Homework 1 due today, 4:30pm Homework 2 out, due next Tuesday Project 1 out, due next Thursday Questions?

Perl. Perl. Perl. Which Perl

Introduction to Unix The Windows User perspective. Wes Frisby Kyle Horne Todd Johansen

Sub-Topic 1: Quoting. Topic 2: More Shell Skills. Sub-Topic 2: Shell Variables. Referring to Shell Variables: More

GNU Bash. An Introduction to Advanced Usage. James Pannacciulli Systems (mt) Media Temple

Script Programming Systems Skills in C and Unix

Unix Guide. Meher Krishna Patel. Created on : Octorber, 2017 Last updated : December, More documents are freely available at PythonDSP

Advanced bash scripting

Cisco IOS Shell. Finding Feature Information. Prerequisites for Cisco IOS.sh. Last Updated: December 14, 2012

5/20/2007. Touring Essential Programs

Implementation of a simple shell, xssh

CSCI 2132 Final Exam Solutions

Introduction to UNIX. Introduction. Processes. ps command. The File System. Directory Structure. UNIX is an operating system (OS).

Introduction to UNIX. CSE 2031 Fall November 5, 2012

Transcription:

Titolo presentazione Piattaforme Software per la Rete sottotitolo BASH Scripting Milano, XX mese 20XX A.A. 2016/17, Alessandro Barenghi

Outline 1) Introduction to BASH 2) Helper commands 3) Control Flow constructs 4) Plumbing and Input/Output 2/27

Introduction to BASH

Shell scripts A bash script is simply a ASCII text file, which is fed to a command interpreter Every script should always begin with the hashbang directive: #!/path/to/interpreter In case of BASH it usually is: #!/bin/bash Any executable can be used as an interpreter In case no hashbang is specified, the default interpreter is used (usually /bin/sh) 4/27

Shell Variables By default, the variables have global visibility in the script Bash variables are untyped Variable assignment: PLUTO= blablabla The common convention is to have ALL_UPPERCASE names (not mandatory) In order to use a variable, you have to use the $ operator: $PLUTO 5/27

Special Variables Command-line parameters: $0, $1, $2, : similar to the C s argv $*: single variable with the concatenated parameters $@: array of parameters as tokenized by bash $#: number of parameters $?: return value of the previous command 6/27

Special Variables Environmental variables: Exported variables (maybe outside your script) Can be accessed by running programs (e.g. through the C getenv function) export and unset commands in BASH 7/27

Helper commands

Sequence of numbers seq command generates a sequence of numbers: Syntax: seq [first] [increment] last -f format -w -s SEP : printf-style notation to specify the format string : add padding zeros to equalize width : use SEP as separator instead the default one (\n) 9/27

Concatenation, splitting : concatenate file passed as input or as parameters to stdout : splits an input file into multiple output ones, with a given discipline cat split -l N : go to next file after N lines and tail print to stdout the first or the last 10 lines of a file (number of lines can be modified by -n N ) head 10/27

Arithmetic operations Performing integer arithmetic operations in BASH are performed through arithmetic expansion: expr can be used with backticks: CINQUE=`expr 4 + 1` let, $(( )), $[ ] as evaluation of a string: let ABC=$A + 3 ABC=$(( $A + 3 )) ABC=$[ $A + 3 ] 11/27

Arithmetic operations What about floating point operations? In BASH you can t because you don t need it. If you really think you need it you are probably wrong. But if you can use any command able to compute them: Tipical commands: Any other scripting language: python bc awk zsh R perl Be aware of the portability! 12/27

Control Flow constructs

Script level control flow exec COMMAND replace the current shell without creating a new process exit the scripts. If NUM is provided, returns the value NUM (often non-zero value mean error) exit [NUM] source FILENAME execute FILENAME in the current context 14/27

The `if` construct Syntax: if <condition>; then <statements>; else <statements>; fi The output of a command can be used as a condition: returned value == 0 (successful execution) TRUE returned value!= 0 (error) FALSE The test command is useful in many situation: returns true if the file exists test -e <filename> test! -e <filename> test <string1> = <string2> returns true if the file does not exist returns true if the strings match The operator [] can be used as synonym of test 15/27

The `for` construct Syntax: for <variable> in <list>; do <statements>; done Loop similar to foreach construct in programming languages By default split over whitespaces, tabs and newlines Can be changed properly setting IFS variable (i.e. Internal Field Separator) List can be obtained by other commands, e.g.: for i in `seq 1 10`; do echo $i; done 16/27

The `for` construct The for construct can be used to iterate over filenames: All files in the current directory: for i in *; rm $i; done Only jpg files: for i in *.jpg; cp $i $RANDOM.jpg; done Only files starting with abc with ext.sh in folder mistero: for i in mistero/abc*.sh; chmod +x $i.sh; done 17/27

The `while` construct Syntax: while <condition>; do <statements>; done <condition> follows the same rules of if construct Example: i=5 while [ $i -gt 0 ] do echo $i let i=$i-1 done 18/27

The `case` construct Similar to switch-case construct in C Syntax: case <variable> in <pattern>) <statements>;; <pattern>) <statements>;;... esac <pattern> can be a regex: * : indicates zero or more characters [] : indicates a character class, e.g. [0-5] 19/27

Functions Syntax for function declaration: <function_name> () { <statements> } All the functions are assumed to have variable arguments, accessible via the usual special variables ($1, $2,, $@,...) Syntax for function invocation: <function_name> [arg1 arg2 arg3...] Warning: the function body is not parsed until the function is invoked, latent syntax errors may hide there! 20/27

Plumbing e Input/Output

BASH Plumbing UNIX Philosophy: keep program small and simple, combine them to obtain complex effects BASH provides the user constructs to: Concatenate the standard output files of a command into standard input of another one Feed any of them with/to a file on the disk Duplicate data flows or merge them 22/27

Redirection Redirection operators with files: a>b : redirect the stdout of a to file b (eventually overwrite) a<b : redirect the file b to the stdin of a a >> b : redirect the stdout of a to file b (append) Redirection can be used to reference file descriptor: cmd 1>&2 : redirect output to stderr Common file descriptors: stdin:0, stdout:1, stderr:2 23/27

BASH Plumbing Pipe operator: : redirect the stdout of cmd1 into the stdin of cmd2 (this is not bidirectional!) cmd1 cmd2 Some useful targets: cmd1 less or cmd1 sort : sorts by line the text passed as input cmd1 uniq : returns unique occurrences of the lines cmd1 > /dev/null cmd1 more to read long text : a special file that discards anything 24/27

The `grep` command The It can be used with stdin or with a filename: grep command prints lines that match a pattern command grep pattern e.g. ls -l grep txt grep pattern filename.txt e.g. grep ERROR log.txt Matching can be inverted with -i -v option option provides a case-insensitive matching 25/27

The `tee` command Name from the idraulic T-splitter Syntax: Example: tee <filename> ls -l tee file.txt less ls -l tee file.txt less stdout stdin file.txt Figure from https://commons.wikimedia.org/wiki/file:tee.svg (GFDL licence) 26/27

Control buffers size stdin, stdout and stderr are buffered You can use the buffer Useful when dealing with interactive application like stdbuf [-i N] [-o N] [-e N] command to control the size of socat or netcat Figure from https://commons.wikimedia.org/wiki/file:tee.svg (GFDL licence) 27/27