SlideShare a Scribd company logo
#LinuxDay2016
http://lugroma3.org/
The Unbearable
Lightness
Extending the Bash shell
I have a natural revulsion to any operating system that
shows so little planning as to have named all of its
commands after digestive noises (awk, grep, fsck, nroff).
Source: The UNIX HATERS Handbook
Shellshocks
CVE-2014-6271
env x='() { :;}; echo vulnerable' bash -c "echo this is a test"
CVE-2014-7169
env X='() { (a)=>' bash -c "echo date"; cat echo
Weaknesses
http://mywiki.wooledge.org/BashWeaknesses
Speed
It's too big and too slow.
Source: man bash
Everything is text
egrep '^To:|^Cc:' /var/spool/mail/$USER | 
cut -c5- | 
awk '{ for (i = 1; i <= NF; i++) print $i }' | 
sed 's/,//g' | grep -v $USER | sort | uniq
Floating point
$ echo $((3/2))
1
Multidimensional
arrays
$ array=('d1=(v1 v2 v3)' 'd2=(v1 v2 v3)')
$ for elt in "${array[@]}";do eval $elt;done
$ echo "d1 ${#d1[@]} ${d1[@]}"
$ echo "d2 ${#d2[@]} ${d2[@]}"
Sorting
$ array=(2 1 0)
$ IFS=$'n' sorted=($(sort <<<"${array[*]}"))
$ unset IFS
$ echo ${sorted[*]}
0 1 2
Variable typing
$ declare -i x
$ x=foo
$ echo $x
0
Variable scope
Local vs Global vs Environment
Return values
Bash functions don't return anything (except numbers in the
range 0-255); they only produce output streams
Passing by
reference
function swap()
{
eval "$1=${!2} $2=${!1}"
}
$ x=a y=b
$ swap x y
b a
Function scope
$ shopt -s extdebug
$ function foo() { echo $qux ; echo ${BASH_ARGV[0]} ; }
$ function bar() { local qux=thud ; foo ; }
$bar baz
thud
baz
Function collapsing
chatter() {
if [[ $verbose ]]; then
chatter() {
echo "$@"
}
chatter "$@"
else
chatter() {
:
}
fi
}
No closures
No first-order functions, no lambdas, ...
Try/catch
trap
Exception handling
set -e
Process
management
select? poll? events?
Parsing
sed 
-ne "s|^($s):|1|" 
-e "s|^($s)($w)$s:$s["'](.*)["']$s$|1$fs2$fs3|p" 
-e "s|^($s)($w)$s:$s(.*)$s$|1$fs2$fs3|p"
Binary data
dd if=/dev/brain of=/dev/null
Paradigms
OO? Functional? Flow-driven? Reflective?
Security
Did you say dropping permissions?
Large programs
source foobar.sh
Debugging
set -x
Subshell Dilemma
$ c=0; ls * | while read i; do ((c++)); done; echo $c
0
Bashisms
eval x=$$x
Portability
It is easier to port a shell than a shell script.
Source: Larry Wall
Why does it
matter?
DRY
Don't write scripts, write libraries
DevOps
Python/Ruby/Scala/... are not ubiquitous
Legacy code
Attempts
bang.sh
the "b" namespace
bashinator
function createDirectory() {
local directory=${1}
if [[ -z "${directory}" ]]; then
__msg err "argument 1 (directory) missing"
return 2
fi
__msg debug "directory: ${directory}"
if ! mkdir -p "${directory}" >> "$_{L}" 2>&1; then
__msg err "failed to create directory '${directory}'"
return 2
fi
return 0
}
bash automated
testing system
@test "addition using bc" {
result="$(echo 2+2 | bc)"
[ "$result" -eq 4 ]
}
@test "addition using dc" {
result="$(echo 2 2+p | dc)"
[ "$result" -eq 4 ]
}
bash infinity
import util/namedParameters util/class
class:Human() {
public string name
public integer height
public array eaten
Human.__getter__() {
echo "I'm a human called $(this name), $(this height) cm tall."
}
...
}
bash manager
hello:
p1=World!
$ ./bash_manager.sh -h /tmp/helloHome
Hello World!
bash toolbox
alias fail='printf "${BASH_SOURCE##*/}: ${FU ...
alias debug='printf "${BASH_SOURCE##*/}: ${FU ...
alias caller='nm=$(builtin caller 0); nm=${nm% ...
bashworks
Inversion of control: the overall program's flow of control
is not dictated by the caller, but by the framework.
Polite functions: Generic reuseable functions usually take a
module name string argument.
blp
minimalist approach
log4sh
# set alternative 'nc' command
log4sh_setAlternative nc /bin/nc
# add and configure a SyslogAppender that logs to a remote host
logger_addAppender mySyslog
appender_setType mySyslog SyslogAppender
appender_syslog_setFacility mySyslog local4
appender_syslog_setHost mySyslog somehost
appender_activateOptions mySyslog
# say Hello to the world
logger_info 'Hello, world'
mbfl
mbfl_argv_all_files || 
exit_because_wrong_command_line_arguments
for item in "${ARGV[@]}"
do
test "${script_option_AUTO}" = yes && {
size=$(mbfl_file_get_size "${item}")
...
oobash
## class Dialog
Dialog=(
# Explicit definition is needed to make inheritance possible.
function __new__ = Dialog::__new__
function __delete__ = Dialog::__delete__
)
ticktick
. ticktick.sh
function printEmployees() {
for employee in ``people.Engineering.items()``; do
printf " - %sn" ${!employee}
done
}
Bashlets
Modular
source bashlet datatype/version
bash$$ version sort 1.44 1.4 1.4.4 1.4.4a 1.4-1234
Git integration
General-purpose
IPC, math, network, OS-abstraction, parsers, UX, ...
Extensible
Plugins for web protocols, databases, RCS, ...
Smart autoloading
Via introspection
Work in progress
Colophon
vim, Hovercraft!, CentOS Linux 7.2
exit 0
Roberto Reale
https://bashlets.sh
https://github.com/bashlets

More Related Content

PDF
Ansible, Simplicity, and the Zen of Python
PDF
Docker tips & tricks
PPT
Unix Shell Scripting Basics
PPTX
Unix shell scripting
PPT
Unix Shell Scripting Basics
PDF
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
PPTX
Unix shell scripting basics
PDF
COSCUP2012: How to write a bash script like the python?
Ansible, Simplicity, and the Zen of Python
Docker tips & tricks
Unix Shell Scripting Basics
Unix shell scripting
Unix Shell Scripting Basics
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Unix shell scripting basics
COSCUP2012: How to write a bash script like the python?

What's hot (20)

PDF
Ansible for beginners ...?
PDF
Apache Hadoop for System Administrators
PPTX
Bash Shell Scripting
PDF
Beautiful Bash: Let's make reading and writing bash scripts fun again!
PDF
Shell scripting
PDF
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
PPT
Bash shell
PPTX
2009 cluster user training
PPT
Shell Scripting
PDF
Go-Couchbase Golang Paris 2015/12/17
PDF
Introduction to shell scripting
PDF
Ansible - Swiss Army Knife Orchestration
PPTX
Comets notes
PDF
Shell scripting
PPTX
Using Ansible Dynamic Inventory with Amazon EC2
PDF
DevSecCon Asia 2017: Guillaume Dedrie: A trip through the securitiy of devops...
PPTX
Ansible fest Presentation slides
PPT
Unix And Shell Scripting
ODP
DevChatt 2010 - *nix Cmd Line Kung Foo
PDF
Ansible tips & tricks
Ansible for beginners ...?
Apache Hadoop for System Administrators
Bash Shell Scripting
Beautiful Bash: Let's make reading and writing bash scripts fun again!
Shell scripting
Introduction to Bash Scripting, Zyxware Technologies, CSI Students Convention...
Bash shell
2009 cluster user training
Shell Scripting
Go-Couchbase Golang Paris 2015/12/17
Introduction to shell scripting
Ansible - Swiss Army Knife Orchestration
Comets notes
Shell scripting
Using Ansible Dynamic Inventory with Amazon EC2
DevSecCon Asia 2017: Guillaume Dedrie: A trip through the securitiy of devops...
Ansible fest Presentation slides
Unix And Shell Scripting
DevChatt 2010 - *nix Cmd Line Kung Foo
Ansible tips & tricks
Ad

Similar to The Unbearable Lightness: Extending the Bash shell (20)

PDF
Lets make better scripts
PDF
Jenkins pipeline -- Gentle Introduction
PDF
Deploying Docker (Provisioning /w Docker + Chef/Puppet) - DevopsDaysPGH
PDF
BASH Variables Part 1: Basic Interpolation
PDF
Unleash your inner console cowboy
PDF
Bash is not a second zone citizen programming language
PPTX
Linux Shell Scripting
PPTX
10 tips for making Bash a sane programming language
PDF
Discover Dart(lang) - Meetup 07/12/2016
PDF
Discover Dart - Meetup 15/02/2017
PDF
PDF
One-Liners to Rule Them All
PDF
os lab assignment.pdf
PPTX
Jenkins shared librar
PPTX
Dtalk shell
PPT
390aLecture05_12sp.ppt
PPTX
Get-Help: An intro to PowerShell and how to Use it for Evil
PDF
Buildr In Action @devoxx france 2012
KEY
JavaScript Growing Up
PDF
Using ngx_lua in UPYUN
Lets make better scripts
Jenkins pipeline -- Gentle Introduction
Deploying Docker (Provisioning /w Docker + Chef/Puppet) - DevopsDaysPGH
BASH Variables Part 1: Basic Interpolation
Unleash your inner console cowboy
Bash is not a second zone citizen programming language
Linux Shell Scripting
10 tips for making Bash a sane programming language
Discover Dart(lang) - Meetup 07/12/2016
Discover Dart - Meetup 15/02/2017
One-Liners to Rule Them All
os lab assignment.pdf
Jenkins shared librar
Dtalk shell
390aLecture05_12sp.ppt
Get-Help: An intro to PowerShell and how to Use it for Evil
Buildr In Action @devoxx france 2012
JavaScript Growing Up
Using ngx_lua in UPYUN
Ad

More from Roberto Reale (13)

PPTX
eInvoicing adoption in Italy & CEF projects
PDF
eProcurement governance: i nodi da sciogliere
PPTX
Governing Information Security
PDF
Società Civile: diritto di accesso e sicurezza in rete
PDF
Tecnologie emergenti: opportunità, sfide, governance
PDF
Blockchain for Business
PPTX
Politically correct. Sentiment analysis of Italian political texts
PDF
Beyond relational: «neural» DBMS?
PDF
La Strategia per la Crescita Digitale 2014-2020
PDF
Homo Digitalis: Metamorfosi dell'identità
PPTX
The History of Technological Anxiety and the Future of Economic Growth: Is Th...
PDF
All'ombra del Leviatano: Filesystem in Userspace
PDF
Fog and the City: an urbanist's perspective
eInvoicing adoption in Italy & CEF projects
eProcurement governance: i nodi da sciogliere
Governing Information Security
Società Civile: diritto di accesso e sicurezza in rete
Tecnologie emergenti: opportunità, sfide, governance
Blockchain for Business
Politically correct. Sentiment analysis of Italian political texts
Beyond relational: «neural» DBMS?
La Strategia per la Crescita Digitale 2014-2020
Homo Digitalis: Metamorfosi dell'identità
The History of Technological Anxiety and the Future of Economic Growth: Is Th...
All'ombra del Leviatano: Filesystem in Userspace
Fog and the City: an urbanist's perspective

Recently uploaded (20)

PDF
System and Network Administraation Chapter 3
PDF
medical staffing services at VALiNTRY
PDF
Understanding Forklifts - TECH EHS Solution
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
L1 - Introduction to python Backend.pptx
PPTX
Essential Infomation Tech presentation.pptx
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
Nekopoi APK 2025 free lastest update
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PPTX
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 41
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PDF
Softaken Excel to vCard Converter Software.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
PPTX
Reimagine Home Health with the Power of Agentic AI​
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
PDF
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
PDF
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf
System and Network Administraation Chapter 3
medical staffing services at VALiNTRY
Understanding Forklifts - TECH EHS Solution
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
L1 - Introduction to python Backend.pptx
Essential Infomation Tech presentation.pptx
Design an Analysis of Algorithms I-SECS-1021-03
Nekopoi APK 2025 free lastest update
wealthsignaloriginal-com-DS-text-... (1).pdf
How to Migrate SBCGlobal Email to Yahoo Easily
Lecture 3: Operating Systems Introduction to Computer Hardware Systems
Internet Downloader Manager (IDM) Crack 6.42 Build 41
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Softaken Excel to vCard Converter Software.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
T3DD25 TYPO3 Content Blocks - Deep Dive by André Kraus
Reimagine Home Health with the Power of Agentic AI​
VVF-Customer-Presentation2025-Ver1.9.pptx
Audit Checklist Design Aligning with ISO, IATF, and Industry Standards — Omne...
Raksha Bandhan Grocery Pricing Trends in India 2025.pdf

The Unbearable Lightness: Extending the Bash shell