SlideShare a Scribd company logo
Naughty & Nice
Bash Features
Nati Cohen / Fewbytes
@nocoot
$ echo $SHELL
/bin/bash
$ echo $SHELL
/bin/bash
https://docs.chef.io/resource_bash.html
https://github.com/puppetlabs/puppetlabs-mysql/blob/master/templates/mysqlbackup.sh.erb
Today
Not Today
Shellshock
Docker
Docker
Functions
Functions
function is_it_on {
ping -c 1 $1 &>/dev/null
}
$ is_it_on www.facebook.com || echo “OMG we’re doomed”
Nice Functions
Nice Functions
function it_crowd {
# Turn it off and on again
ssh $1 reboot
# Is it off yet?
while is_it_on $1; do :; done
# Is it on yet?
while ! is_it_on $1; do :; done
}
$ it_crowd mycomputer
: [arguments]
No effect; the command does
nothing beyond expanding
arguments and performing any
specified redirections.
A zero exit code is returned.
http://git.savannah.gnu.org/cgit/bash.git/tree/builtins/colon.def
Functions
function is_it_on {
ping -c 1 $1 &>/dev/null
}
$ is_it_on www.facebook.com || echo “OMG we’re doomed”
Compact Functions
is_it_on (){ ping -c 1 $1 &>/dev/null;}
$ is_it_on www.facebook.com || echo “OMG we’re doomed”
is_it_on{ ping -c 1 $1 &>/dev/null;}
bash: syntax error near unexpected token `}'
is_it_on(){ping -c 1 $1 &>/dev/null;}
bash: syntax error near unexpected token `{ping'
is_it_on{ ping -c 1 $1 &>/dev/null}
>
Cmpct Functions
:(){ ping -c 1 $1 &>/dev/null;}
$ : www.facebook.com || echo “OMG we’re doomed”
Naughty Functions (Local)
: (){ :;}
$ :
Segmentation fault (core dumped)
Naughty Functions (Global)
: (){ : $1$1;}
$ : :
bash: xrealloc: .././subst.c:687: cannot allocate
18446744071562068096 bytes (23624826880 bytes allocated)
Function definition
Function call
Parameter
Famous Naughty Functions
:(){ :|:&}
$ :
bash: fork: Cannot allocate memory
ENOMEM Cannot allocate
sufficient memory to allocate a
task structure for the child,
or to copy those parts of
the caller's context that need
to be copied.
CLONE(2)
Image taken from: http://askubuntu.com/a/159499
Globbing
Globbing
Pathname expansion using pattern matching
$ ls -ld /etc/cron*
->
$ ls -ld /etc/cron.d /etc/cron.daily /etc/cron.hourly
/etc/cron.monthly /etc/crontab /etc/cron.weekly
$ ls -ld /etcccc/*
->
$ ls -ld /etcccc/*
Globbing
$ mkdir iknowglobbing
$ cd iknowglobbing
$ touch stat
$ touch x
$ *
->
$ stat x
File: ‘x’
Size: 0 Blocks: 0 IO Block: 4096 regular empty file
Device: 802h/2050d Inode: 4329283 Links: 1
Access: (0664/-rw-rw-r--) Uid: ( 1000/ nati) Gid: ( 1000/ nati)
Access: 2015-12-10 17:03:23.798313371 +0200
Modify: 2015-12-10 17:03:23.798313371 +0200
Change: 2015-12-10 17:03:23.798313371 +0200
Birth: -
Nice Globbing (shopt -s extglob)
!(<PATTERN-LIST>) - anything except
$ rm -rf ~/Downloads/!(*.pdf|*.doc?|*.ods|*.xls?)
?(<PATTERN-LIST>) - zero or one
*(<PATTERN-LIST>) - zero or more
+(<PATTERN-LIST>) - one or more
@(<PATTERN-LIST>) - exactly one
Nice Globbing (shopt -s <superpower>)
dotglob
Bash will also expand ‘.’ as part of glob (inc: `.`
`..`)
globstar
‘**’ will match all files and zero or more directories
nocaseglob
case-insensitive globbing
nullglob / failglob
when globbing fails expand empty string / fail with
Naughty Globbing
# Print all files in depth 10:
$ echo /*/*/*/*/*/*/*/*/*/*
# hogs your CPU, performs IOs, consumes memory
Out of memory: Kill process 3769 (bash) score 792 or
sacrifice child
Killed process 3769 (bash) total-vm:23463052kB, anon-
rss:20065304kB, file-rss:0kB
BUT
Why???
o_O
Let’s build a Christmas tree
$ mkdir -p {a1,a2,a3}/{b1,b2,b3}/{c1,c2,c3}
.
a2 a3a1
b2 b3b1b2 b3b1 b2 b3b1
How do you glob a tree?
$ strace -e openat bash -c 'echo */*/*'
openat(AT_FDCWD, ".", <FLAGS>) = 3
getdents(3, /* 5 entries */, 32768) = 120
openat(AT_FDCWD, "a2", <FLAGS>) = 3
openat(AT_FDCWD, "a3", <FLAGS>) = 3
openat(AT_FDCWD, "a1", <FLAGS>) = 3
openat(AT_FDCWD, "a2/b1", <FLAGS>) = 3
openat(AT_FDCWD, "a2/b3", <FLAGS>) = 3
openat(AT_FDCWD, "a2/b2", <FLAGS>) = 3
openat(AT_FDCWD, "a3/b1", <FLAGS>) = 3
openat(AT_FDCWD, "a3/b3", <FLAGS>) = 3
...
Where is the poop?
Image source: http://www.cse.unsw.edu.au/~billw/Justsearch.html
Size per file?
12b # avg. file name length
+
52b # avg. full path length in depth 10
=
64b
How many files?
$ for i in {1..10}; do echo -n "depth $i: "; find / -mindepth
$((i-1)) -maxdepth $i 2>/dev/null | wc -l; done
depth 1: 30
depth 2: 1418
depth 3: 21076
depth 4: 63150
depth 5: 199812
depth 6: 432928
depth 7: 568426
depth 8: 617698
depth 9: 511480
depth 10: 320827
BUT
511480 * 64b = 32mb
o_O
ltrace to the rescue
strlen("p7zip-full") = 10
memset(0x88eff08, '337', 58) = 0x88eff08
strcpy(0x88eff08,
"/proc/18256/root/proc/2628/root/usr/share/doc")= 0x88eff08
strcpy(0x88eff36, "p7zip-full") = 0x88eff36
strlen("mount") = 5
memset(0x88eff88, '337', 53) = 0x88eff88
strcpy(0x88eff88,
"/proc/18256/root/proc/2628/root/usr/share/doc")= 0x88eff88
strcpy(0x88effb6, "mount")= 0x88effb6
/proc/<PID>/root
“per-process root of the filesystem, set by the chroot(2)”
usually symlink to /
depth 1: 30
depth 2: 1418
depth 3: 21076
depth 4: 63150
depth 5: 199812
depth 6: 432928
depth 7: 568426
depth 8: 617698
depth 9: 511480
depth 10: 320827
Assuming root and 100 processes:
(100*432928 +
100*100*21076) * 64b
= 15.1gb
Naughty Globbing - Recap
$ echo /*/*/*/*/*/*/*/*/*/*
64b per file
Keeps previous level in memory (BFS)
Follows symlinks over and over
/proc/PID/root
/proc/PID/cwd
Command Substitution
Command Substitution
# old-style
$ echo All you need is `basename $0`
All you need is bash
# new-style
$ echo $(basename $0) is all you need
bash is all you need
# new-style is cool
bobs_cred="$(echo bob:"$(shuf -n4 /usr/share/dict/words | tr
-d 'n')" | chpasswd -S -c SHA512)"
nested commands
nested double-quotes
Nice Command Process Substitution
# Compare filesystem features
$ diff <(dumpe2fs -h /dev/sdb1) <(dumpe2fs -h /dev/sdc1)
->
$ diff /dev/fd/63 /dev/fd/62
lr-x------ 1 nati nati ... /dev/fd/62 -> pipe:[142006]
lr-x------ 1 nati nati ... /dev/fd/63 -> pipe:[142004]
# Write bad blocks to a compressed log and rsyslogd
$ dumpe2fs -b /dev/sda1 | tee >(gzip >> bad_blocks.log.gz) |
logger -t bad_blocks --
Naughty Command Substitution
$ echo `yes Let it snow`
bash: xrealloc: .././subst.c:5273: cannot allocate
18446744071562067968 bytes (4298260480 bytes allocated)
$ yes somestring
somestring
somestring
somestring
somestring
somestring
...
Naughty Process Substitution
# Remember me?
$ :(){ : <(:);}
$ :
bash: fork: Cannot allocate memory
Pipelines
ls | wc -l
The STDOUT of ls is connected to the STDIN of wc -l
Each command is executed as a separate process
# What if I also want STDERR?
$ ls 2>&1 | wc -l
$ ls |& wc -l
Nice Pipelines: exit code(s)
# The following pipeline is a huge success
$ backup.sh | aws s3 cp - s3://my-bkt/backup.gz | echo Yay
$ echo $? # Always 0
# Solution 1
$ set -o pipefail # pipes return rightmost non-zero
Nice Pipelines: exit code(s)
# Solution 2
$ ls | bogus_command | wc
bogus_command: command not found
0 0 0
$ echo ${PIPESTATUS[@]} # array of exit status values
0 127 0
http://tldp.org/LDP/abs/html/internalvariables.html#PIPESTATUSREF
Nice Pipelines (shopt - s lastpipe)
# The following only works when job control is off
# How many files in /tmp?
myvar=0
ls /tmp | wc -l | read myvar
echo $myvar files in /tmp # Always 0! why?
# How many files in /tmp?
shopt -s lastpipe
myvar=0
ls /tmp | wc -l | read myvar
echo $myvar files in /tmp
Naughty Pipelines
curl http://install.myawesomefullstackapp.io | bash
Someone can take over install.myawesomefullstackapp.io
So what?
0_0
Naughty Pipelines
import random
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return random.choice([':(){ :;} :',
':(){ : $1$1;} : :',
':(){ :|:&} :',
'echo /*/*/*/*/*/*/*/*/*/*',
'echo `yes Let it snow`',
':(){ : <(:);} :' ])
if __name__ == "__main__":
app.run()
Naughty Pipelines
What about network failures?
Do you trust curl? is it a function/alias?
Do you trust myawesomefullstackapp.io?
curl http://install.myawesomefullstackapp.io | bash
Someone can take over install.myawesomefullstackapp.io
Naughty Pipelines http://curlpipesh.tumblr.com
Thank You!
Questions?
Nati Cohen / Fewbytes
@nocoot
References
Advanced Bash-Scripting Guide
http://www.tldp.org/LDP/abs/html/index.html
Bash Git Repository
http://git.savannah.gnu.org/cgit/bash.git
Create a memory leak, without any fork bombs
http://codegolf.stackexchange.com/a/24488

More Related Content

What's hot

node ffi
node ffinode ffi
node ffi
偉格 高
 
Cluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeCluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in Practice
Steffen Wenz
 
Crystal Rocks
Crystal RocksCrystal Rocks
Crystal Rocks
Brian Cardiff
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
Ian Barber
 
PyData Berlin Meetup
PyData Berlin MeetupPyData Berlin Meetup
PyData Berlin Meetup
Steffen Wenz
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
Ian Barber
 
Go Containers
Go ContainersGo Containers
Go Containers
jgrahamc
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
jgrahamc
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
Ian Barber
 
7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)
Steven Francia
 
BOSH deploys distributed systems, and Diego runs any containers
BOSH deploys distributed systems, and Diego runs any containersBOSH deploys distributed systems, and Diego runs any containers
BOSH deploys distributed systems, and Diego runs any containers
Benjamin Gandon
 
Clojure + MongoDB on Heroku
Clojure + MongoDB on HerokuClojure + MongoDB on Heroku
Clojure + MongoDB on Heroku
Naoyuki Kakuda
 
faastCrystal
faastCrystalfaastCrystal
faastCrystal
Sachirou Inoue
 
Gitosis on Mac OS X Server
Gitosis on Mac OS X ServerGitosis on Mac OS X Server
Gitosis on Mac OS X ServerYasuhiro Asaka
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1
Leandro Lima
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
Leandro Lima
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
Yusuke Kita
 
ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale Subbu Allamaraju
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
Amaury Bouchard
 

What's hot (20)

node ffi
node ffinode ffi
node ffi
 
Cluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in PracticeCluj Big Data Meetup - Big Data in Practice
Cluj Big Data Meetup - Big Data in Practice
 
Crystal Rocks
Crystal RocksCrystal Rocks
Crystal Rocks
 
ZeroMQ Is The Answer
ZeroMQ Is The AnswerZeroMQ Is The Answer
ZeroMQ Is The Answer
 
PyData Berlin Meetup
PyData Berlin MeetupPyData Berlin Meetup
PyData Berlin Meetup
 
ZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 VersionZeroMQ Is The Answer: DPC 11 Version
ZeroMQ Is The Answer: DPC 11 Version
 
Go Containers
Go ContainersGo Containers
Go Containers
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Go Memory
Go MemoryGo Memory
Go Memory
 
ZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made SimpleZeroMQ: Messaging Made Simple
ZeroMQ: Messaging Made Simple
 
7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)
 
BOSH deploys distributed systems, and Diego runs any containers
BOSH deploys distributed systems, and Diego runs any containersBOSH deploys distributed systems, and Diego runs any containers
BOSH deploys distributed systems, and Diego runs any containers
 
Clojure + MongoDB on Heroku
Clojure + MongoDB on HerokuClojure + MongoDB on Heroku
Clojure + MongoDB on Heroku
 
faastCrystal
faastCrystalfaastCrystal
faastCrystal
 
Gitosis on Mac OS X Server
Gitosis on Mac OS X ServerGitosis on Mac OS X Server
Gitosis on Mac OS X Server
 
Workshop on command line tools - day 1
Workshop on command line tools - day 1Workshop on command line tools - day 1
Workshop on command line tools - day 1
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 
Writing a compiler in go
Writing a compiler in goWriting a compiler in go
Writing a compiler in go
 
ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale ql.io: Consuming HTTP at Scale
ql.io: Consuming HTTP at Scale
 
Créer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heureCréer une base NoSQL en 1 heure
Créer une base NoSQL en 1 heure
 

Viewers also liked

REGLAMENTO CUATREADA BACH
REGLAMENTO CUATREADA BACHREGLAMENTO CUATREADA BACH
REGLAMENTO CUATREADA BACHyogui1970
 
Amor eterno
Amor eternoAmor eterno
Amor eterno
Constanza Maté
 
Stki summit2013 infra_pini sigaltechnologies_v5 final
Stki summit2013 infra_pini sigaltechnologies_v5 finalStki summit2013 infra_pini sigaltechnologies_v5 final
Stki summit2013 infra_pini sigaltechnologies_v5 final
Pini Cohen
 
Le zanzare sono un tormento? Vediamo come difenderci
Le zanzare sono un tormento? Vediamo come difenderciLe zanzare sono un tormento? Vediamo come difenderci
Le zanzare sono un tormento? Vediamo come difenderci
Vivere La Casa in Campagna
 
Webconferencing adobe e-learning_day_2011_stoller-schai
Webconferencing adobe e-learning_day_2011_stoller-schaiWebconferencing adobe e-learning_day_2011_stoller-schai
Webconferencing adobe e-learning_day_2011_stoller-schai
Dr. Daniel Stoller-Schai
 
Tema 2. la revolución industrial
Tema 2. la revolución industrialTema 2. la revolución industrial
Tema 2. la revolución industrialjmap2222
 
Marktforschung mit einfachen Mitteln
Marktforschung mit einfachen MittelnMarktforschung mit einfachen Mitteln
Marktforschung mit einfachen Mitteln
Jörg Hoewner
 
La BolsaenelañO2009
La BolsaenelañO2009La BolsaenelañO2009
La BolsaenelañO2009
IvanAleman
 
Minuta acensores empresa schindler 03 21-07-2011
Minuta acensores empresa schindler 03 21-07-2011Minuta acensores empresa schindler 03 21-07-2011
Minuta acensores empresa schindler 03 21-07-2011Antonio Cazorla
 
nanopub-java: A Java Library for Nanopublications
nanopub-java: A Java Library for Nanopublicationsnanopub-java: A Java Library for Nanopublications
nanopub-java: A Java Library for Nanopublications
Tobias Kuhn
 
Integradora I portafolio joran abelino
Integradora I portafolio joran abelinoIntegradora I portafolio joran abelino
Integradora I portafolio joran abelinoMarco Antonio Pineda
 
Primer programador piedras preciosas
Primer programador piedras preciosasPrimer programador piedras preciosas
Primer programador piedras preciosas
Mayerly Martinez
 
La oreja Roja
La oreja RojaLa oreja Roja
La oreja Rojabw24h
 
Resumen el trabajo colaborativo mediante redes
Resumen el trabajo colaborativo mediante redesResumen el trabajo colaborativo mediante redes
Resumen el trabajo colaborativo mediante redesfabiolaflolug
 
oiml_bulletin_april_2015
oiml_bulletin_april_2015oiml_bulletin_april_2015
oiml_bulletin_april_2015Wan Malik
 
Clase 1 (2016) sección s1
Clase 1 (2016) sección s1Clase 1 (2016) sección s1
Clase 1 (2016) sección s1
Suelen Oseida
 

Viewers also liked (20)

Commands[1]
Commands[1]Commands[1]
Commands[1]
 
Flip video communication
Flip video communicationFlip video communication
Flip video communication
 
REGLAMENTO CUATREADA BACH
REGLAMENTO CUATREADA BACHREGLAMENTO CUATREADA BACH
REGLAMENTO CUATREADA BACH
 
Amor eterno
Amor eternoAmor eterno
Amor eterno
 
Debtanu_cv
Debtanu_cvDebtanu_cv
Debtanu_cv
 
Stki summit2013 infra_pini sigaltechnologies_v5 final
Stki summit2013 infra_pini sigaltechnologies_v5 finalStki summit2013 infra_pini sigaltechnologies_v5 final
Stki summit2013 infra_pini sigaltechnologies_v5 final
 
Conquistar es imposible
Conquistar es imposibleConquistar es imposible
Conquistar es imposible
 
Le zanzare sono un tormento? Vediamo come difenderci
Le zanzare sono un tormento? Vediamo come difenderciLe zanzare sono un tormento? Vediamo come difenderci
Le zanzare sono un tormento? Vediamo come difenderci
 
Webconferencing adobe e-learning_day_2011_stoller-schai
Webconferencing adobe e-learning_day_2011_stoller-schaiWebconferencing adobe e-learning_day_2011_stoller-schai
Webconferencing adobe e-learning_day_2011_stoller-schai
 
Tema 2. la revolución industrial
Tema 2. la revolución industrialTema 2. la revolución industrial
Tema 2. la revolución industrial
 
Marktforschung mit einfachen Mitteln
Marktforschung mit einfachen MittelnMarktforschung mit einfachen Mitteln
Marktforschung mit einfachen Mitteln
 
La BolsaenelañO2009
La BolsaenelañO2009La BolsaenelañO2009
La BolsaenelañO2009
 
Minuta acensores empresa schindler 03 21-07-2011
Minuta acensores empresa schindler 03 21-07-2011Minuta acensores empresa schindler 03 21-07-2011
Minuta acensores empresa schindler 03 21-07-2011
 
nanopub-java: A Java Library for Nanopublications
nanopub-java: A Java Library for Nanopublicationsnanopub-java: A Java Library for Nanopublications
nanopub-java: A Java Library for Nanopublications
 
Integradora I portafolio joran abelino
Integradora I portafolio joran abelinoIntegradora I portafolio joran abelino
Integradora I portafolio joran abelino
 
Primer programador piedras preciosas
Primer programador piedras preciosasPrimer programador piedras preciosas
Primer programador piedras preciosas
 
La oreja Roja
La oreja RojaLa oreja Roja
La oreja Roja
 
Resumen el trabajo colaborativo mediante redes
Resumen el trabajo colaborativo mediante redesResumen el trabajo colaborativo mediante redes
Resumen el trabajo colaborativo mediante redes
 
oiml_bulletin_april_2015
oiml_bulletin_april_2015oiml_bulletin_april_2015
oiml_bulletin_april_2015
 
Clase 1 (2016) sección s1
Clase 1 (2016) sección s1Clase 1 (2016) sección s1
Clase 1 (2016) sección s1
 

Similar to Naughty And Nice Bash Features

Apache Hadoop Shell Rewrite
Apache Hadoop Shell RewriteApache Hadoop Shell Rewrite
Apache Hadoop Shell Rewrite
Allen Wittenauer
 
Containers for sysadmins
Containers for sysadminsContainers for sysadmins
Containers for sysadmins
Carlos de Alfonso Laguna
 
Biicode OpenExpoDay
Biicode OpenExpoDayBiicode OpenExpoDay
Biicode OpenExpoDayfcofdezc
 
Im trying to run make qemu-nox In a putty terminal but it.pdf
Im trying to run  make qemu-nox  In a putty terminal but it.pdfIm trying to run  make qemu-nox  In a putty terminal but it.pdf
Im trying to run make qemu-nox In a putty terminal but it.pdf
maheshkumar12354
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them All
egypt
 
Docker and friends at Linux Days 2014 in Prague
Docker and friends at Linux Days 2014 in PragueDocker and friends at Linux Days 2014 in Prague
Docker and friends at Linux Days 2014 in Prague
tomasbart
 
Miscelaneous Debris
Miscelaneous DebrisMiscelaneous Debris
Miscelaneous Debris
frewmbot
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
Geeks Anonymes
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basicsAbhay Sapru
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting BasicsDr.Ravi
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
Ian Barber
 
Dtalk shell
Dtalk shellDtalk shell
Dtalk shell
Miha Mencin
 
Docker - container and lightweight virtualization
Docker - container and lightweight virtualization Docker - container and lightweight virtualization
Docker - container and lightweight virtualization
Sim Janghoon
 
PFIセミナー資料 H27.10.22
PFIセミナー資料 H27.10.22PFIセミナー資料 H27.10.22
PFIセミナー資料 H27.10.22
Yuya Takei
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
brian_dailey
 
What we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at BackstopWhat we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at Backstop
Puppet
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
Yaroslav Tkachenko
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Maarten Mulders
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
Ian Barber
 

Similar to Naughty And Nice Bash Features (20)

Apache Hadoop Shell Rewrite
Apache Hadoop Shell RewriteApache Hadoop Shell Rewrite
Apache Hadoop Shell Rewrite
 
Containers for sysadmins
Containers for sysadminsContainers for sysadmins
Containers for sysadmins
 
Biicode OpenExpoDay
Biicode OpenExpoDayBiicode OpenExpoDay
Biicode OpenExpoDay
 
Im trying to run make qemu-nox In a putty terminal but it.pdf
Im trying to run  make qemu-nox  In a putty terminal but it.pdfIm trying to run  make qemu-nox  In a putty terminal but it.pdf
Im trying to run make qemu-nox In a putty terminal but it.pdf
 
One-Liners to Rule Them All
One-Liners to Rule Them AllOne-Liners to Rule Them All
One-Liners to Rule Them All
 
Docker and friends at Linux Days 2014 in Prague
Docker and friends at Linux Days 2014 in PragueDocker and friends at Linux Days 2014 in Prague
Docker and friends at Linux Days 2014 in Prague
 
Miscelaneous Debris
Miscelaneous DebrisMiscelaneous Debris
Miscelaneous Debris
 
Shell scripting
Shell scriptingShell scripting
Shell scripting
 
dotCloud and go
dotCloud and godotCloud and go
dotCloud and go
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Unix Shell Scripting Basics
Unix Shell Scripting BasicsUnix Shell Scripting Basics
Unix Shell Scripting Basics
 
Debugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 VersionDebugging: Rules And Tools - PHPTek 11 Version
Debugging: Rules And Tools - PHPTek 11 Version
 
Dtalk shell
Dtalk shellDtalk shell
Dtalk shell
 
Docker - container and lightweight virtualization
Docker - container and lightweight virtualization Docker - container and lightweight virtualization
Docker - container and lightweight virtualization
 
PFIセミナー資料 H27.10.22
PFIセミナー資料 H27.10.22PFIセミナー資料 H27.10.22
PFIセミナー資料 H27.10.22
 
NYPHP March 2009 Presentation
NYPHP March 2009 PresentationNYPHP March 2009 Presentation
NYPHP March 2009 Presentation
 
What we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at BackstopWhat we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at Backstop
 
10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language10 tips for making Bash a sane programming language
10 tips for making Bash a sane programming language
 
Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)Building a DSL with GraalVM (VoxxedDays Luxembourg)
Building a DSL with GraalVM (VoxxedDays Luxembourg)
 
Debugging: Rules & Tools
Debugging: Rules & ToolsDebugging: Rules & Tools
Debugging: Rules & Tools
 

Recently uploaded

Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Florence Consulting
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
laozhuseo02
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Brad Spiegel Macon GA
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
Arif0071
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
GTProductions1
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
3ipehhoa
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
ufdana
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
CIOWomenMagazine
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
Rogerio Filho
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
nhiyenphan2005
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
3ipehhoa
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
eutxy
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
Javier Lasa
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
JungkooksNonexistent
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
Gal Baras
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
JeyaPerumal1
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
harveenkaur52
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
3ipehhoa
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
laozhuseo02
 

Recently uploaded (20)

Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdfMeet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
Meet up Milano 14 _ Axpo Italia_ Migration from Mule3 (On-prem) to.pdf
 
The+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptxThe+Prospects+of+E-Commerce+in+China.pptx
The+Prospects+of+E-Commerce+in+China.pptx
 
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptxBridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
Bridging the Digital Gap Brad Spiegel Macon, GA Initiative.pptx
 
test test test test testtest test testtest test testtest test testtest test ...
test test  test test testtest test testtest test testtest test testtest test ...test test  test test testtest test testtest test testtest test testtest test ...
test test test test testtest test testtest test testtest test testtest test ...
 
Comptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guideComptia N+ Standard Networking lesson guide
Comptia N+ Standard Networking lesson guide
 
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
原版仿制(uob毕业证书)英国伯明翰大学毕业证本科学历证书原版一模一样
 
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
一比一原版(CSU毕业证)加利福尼亚州立大学毕业证成绩单专业办理
 
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
APNIC Foundation, presented by Ellisha Heppner at the PNG DNS Forum 2024
 
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
Internet of Things in Manufacturing: Revolutionizing Efficiency & Quality | C...
 
guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...guildmasters guide to ravnica Dungeons & Dragons 5...
guildmasters guide to ravnica Dungeons & Dragons 5...
 
Bài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docxBài tập unit 1 English in the world.docx
Bài tập unit 1 English in the world.docx
 
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
1比1复刻(bath毕业证书)英国巴斯大学毕业证学位证原版一模一样
 
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
一比一原版(LBS毕业证)伦敦商学院毕业证成绩单专业办理
 
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdfJAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
JAVIER LASA-EXPERIENCIA digital 1986-2024.pdf
 
Latest trends in computer networking.pptx
Latest trends in computer networking.pptxLatest trends in computer networking.pptx
Latest trends in computer networking.pptx
 
How to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptxHow to Use Contact Form 7 Like a Pro.pptx
How to Use Contact Form 7 Like a Pro.pptx
 
1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...1.Wireless Communication System_Wireless communication is a broad term that i...
1.Wireless Communication System_Wireless communication is a broad term that i...
 
Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027Italy Agriculture Equipment Market Outlook to 2027
Italy Agriculture Equipment Market Outlook to 2027
 
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
急速办(bedfordhire毕业证书)英国贝德福特大学毕业证成绩单原版一模一样
 
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shopHistory+of+E-commerce+Development+in+China-www.cfye-commerce.shop
History+of+E-commerce+Development+in+China-www.cfye-commerce.shop
 

Naughty And Nice Bash Features

  • 1. Naughty & Nice Bash Features Nati Cohen / Fewbytes @nocoot
  • 7. Functions function is_it_on { ping -c 1 $1 &>/dev/null } $ is_it_on www.facebook.com || echo “OMG we’re doomed”
  • 9. Nice Functions function it_crowd { # Turn it off and on again ssh $1 reboot # Is it off yet? while is_it_on $1; do :; done # Is it on yet? while ! is_it_on $1; do :; done } $ it_crowd mycomputer : [arguments] No effect; the command does nothing beyond expanding arguments and performing any specified redirections. A zero exit code is returned. http://git.savannah.gnu.org/cgit/bash.git/tree/builtins/colon.def
  • 10. Functions function is_it_on { ping -c 1 $1 &>/dev/null } $ is_it_on www.facebook.com || echo “OMG we’re doomed”
  • 11. Compact Functions is_it_on (){ ping -c 1 $1 &>/dev/null;} $ is_it_on www.facebook.com || echo “OMG we’re doomed” is_it_on{ ping -c 1 $1 &>/dev/null;} bash: syntax error near unexpected token `}' is_it_on(){ping -c 1 $1 &>/dev/null;} bash: syntax error near unexpected token `{ping' is_it_on{ ping -c 1 $1 &>/dev/null} >
  • 12. Cmpct Functions :(){ ping -c 1 $1 &>/dev/null;} $ : www.facebook.com || echo “OMG we’re doomed”
  • 13. Naughty Functions (Local) : (){ :;} $ : Segmentation fault (core dumped)
  • 14. Naughty Functions (Global) : (){ : $1$1;} $ : : bash: xrealloc: .././subst.c:687: cannot allocate 18446744071562068096 bytes (23624826880 bytes allocated) Function definition Function call Parameter
  • 15. Famous Naughty Functions :(){ :|:&} $ : bash: fork: Cannot allocate memory ENOMEM Cannot allocate sufficient memory to allocate a task structure for the child, or to copy those parts of the caller's context that need to be copied. CLONE(2) Image taken from: http://askubuntu.com/a/159499
  • 17. Globbing Pathname expansion using pattern matching $ ls -ld /etc/cron* -> $ ls -ld /etc/cron.d /etc/cron.daily /etc/cron.hourly /etc/cron.monthly /etc/crontab /etc/cron.weekly $ ls -ld /etcccc/* -> $ ls -ld /etcccc/*
  • 18. Globbing $ mkdir iknowglobbing $ cd iknowglobbing $ touch stat $ touch x $ * -> $ stat x File: ‘x’ Size: 0 Blocks: 0 IO Block: 4096 regular empty file Device: 802h/2050d Inode: 4329283 Links: 1 Access: (0664/-rw-rw-r--) Uid: ( 1000/ nati) Gid: ( 1000/ nati) Access: 2015-12-10 17:03:23.798313371 +0200 Modify: 2015-12-10 17:03:23.798313371 +0200 Change: 2015-12-10 17:03:23.798313371 +0200 Birth: -
  • 19. Nice Globbing (shopt -s extglob) !(<PATTERN-LIST>) - anything except $ rm -rf ~/Downloads/!(*.pdf|*.doc?|*.ods|*.xls?) ?(<PATTERN-LIST>) - zero or one *(<PATTERN-LIST>) - zero or more +(<PATTERN-LIST>) - one or more @(<PATTERN-LIST>) - exactly one
  • 20. Nice Globbing (shopt -s <superpower>) dotglob Bash will also expand ‘.’ as part of glob (inc: `.` `..`) globstar ‘**’ will match all files and zero or more directories nocaseglob case-insensitive globbing nullglob / failglob when globbing fails expand empty string / fail with
  • 21. Naughty Globbing # Print all files in depth 10: $ echo /*/*/*/*/*/*/*/*/*/* # hogs your CPU, performs IOs, consumes memory Out of memory: Kill process 3769 (bash) score 792 or sacrifice child Killed process 3769 (bash) total-vm:23463052kB, anon- rss:20065304kB, file-rss:0kB BUT Why??? o_O
  • 22. Let’s build a Christmas tree $ mkdir -p {a1,a2,a3}/{b1,b2,b3}/{c1,c2,c3} . a2 a3a1 b2 b3b1b2 b3b1 b2 b3b1
  • 23. How do you glob a tree? $ strace -e openat bash -c 'echo */*/*' openat(AT_FDCWD, ".", <FLAGS>) = 3 getdents(3, /* 5 entries */, 32768) = 120 openat(AT_FDCWD, "a2", <FLAGS>) = 3 openat(AT_FDCWD, "a3", <FLAGS>) = 3 openat(AT_FDCWD, "a1", <FLAGS>) = 3 openat(AT_FDCWD, "a2/b1", <FLAGS>) = 3 openat(AT_FDCWD, "a2/b3", <FLAGS>) = 3 openat(AT_FDCWD, "a2/b2", <FLAGS>) = 3 openat(AT_FDCWD, "a3/b1", <FLAGS>) = 3 openat(AT_FDCWD, "a3/b3", <FLAGS>) = 3 ...
  • 24. Where is the poop? Image source: http://www.cse.unsw.edu.au/~billw/Justsearch.html
  • 25. Size per file? 12b # avg. file name length + 52b # avg. full path length in depth 10 = 64b
  • 26. How many files? $ for i in {1..10}; do echo -n "depth $i: "; find / -mindepth $((i-1)) -maxdepth $i 2>/dev/null | wc -l; done depth 1: 30 depth 2: 1418 depth 3: 21076 depth 4: 63150 depth 5: 199812 depth 6: 432928 depth 7: 568426 depth 8: 617698 depth 9: 511480 depth 10: 320827 BUT 511480 * 64b = 32mb o_O
  • 27. ltrace to the rescue strlen("p7zip-full") = 10 memset(0x88eff08, '337', 58) = 0x88eff08 strcpy(0x88eff08, "/proc/18256/root/proc/2628/root/usr/share/doc")= 0x88eff08 strcpy(0x88eff36, "p7zip-full") = 0x88eff36 strlen("mount") = 5 memset(0x88eff88, '337', 53) = 0x88eff88 strcpy(0x88eff88, "/proc/18256/root/proc/2628/root/usr/share/doc")= 0x88eff88 strcpy(0x88effb6, "mount")= 0x88effb6
  • 28. /proc/<PID>/root “per-process root of the filesystem, set by the chroot(2)” usually symlink to / depth 1: 30 depth 2: 1418 depth 3: 21076 depth 4: 63150 depth 5: 199812 depth 6: 432928 depth 7: 568426 depth 8: 617698 depth 9: 511480 depth 10: 320827 Assuming root and 100 processes: (100*432928 + 100*100*21076) * 64b = 15.1gb
  • 29. Naughty Globbing - Recap $ echo /*/*/*/*/*/*/*/*/*/* 64b per file Keeps previous level in memory (BFS) Follows symlinks over and over /proc/PID/root /proc/PID/cwd
  • 31. Command Substitution # old-style $ echo All you need is `basename $0` All you need is bash # new-style $ echo $(basename $0) is all you need bash is all you need # new-style is cool bobs_cred="$(echo bob:"$(shuf -n4 /usr/share/dict/words | tr -d 'n')" | chpasswd -S -c SHA512)" nested commands nested double-quotes
  • 32. Nice Command Process Substitution # Compare filesystem features $ diff <(dumpe2fs -h /dev/sdb1) <(dumpe2fs -h /dev/sdc1) -> $ diff /dev/fd/63 /dev/fd/62 lr-x------ 1 nati nati ... /dev/fd/62 -> pipe:[142006] lr-x------ 1 nati nati ... /dev/fd/63 -> pipe:[142004] # Write bad blocks to a compressed log and rsyslogd $ dumpe2fs -b /dev/sda1 | tee >(gzip >> bad_blocks.log.gz) | logger -t bad_blocks --
  • 33. Naughty Command Substitution $ echo `yes Let it snow` bash: xrealloc: .././subst.c:5273: cannot allocate 18446744071562067968 bytes (4298260480 bytes allocated) $ yes somestring somestring somestring somestring somestring somestring ...
  • 34. Naughty Process Substitution # Remember me? $ :(){ : <(:);} $ : bash: fork: Cannot allocate memory
  • 36. ls | wc -l The STDOUT of ls is connected to the STDIN of wc -l Each command is executed as a separate process # What if I also want STDERR? $ ls 2>&1 | wc -l $ ls |& wc -l
  • 37. Nice Pipelines: exit code(s) # The following pipeline is a huge success $ backup.sh | aws s3 cp - s3://my-bkt/backup.gz | echo Yay $ echo $? # Always 0 # Solution 1 $ set -o pipefail # pipes return rightmost non-zero
  • 38. Nice Pipelines: exit code(s) # Solution 2 $ ls | bogus_command | wc bogus_command: command not found 0 0 0 $ echo ${PIPESTATUS[@]} # array of exit status values 0 127 0 http://tldp.org/LDP/abs/html/internalvariables.html#PIPESTATUSREF
  • 39. Nice Pipelines (shopt - s lastpipe) # The following only works when job control is off # How many files in /tmp? myvar=0 ls /tmp | wc -l | read myvar echo $myvar files in /tmp # Always 0! why? # How many files in /tmp? shopt -s lastpipe myvar=0 ls /tmp | wc -l | read myvar echo $myvar files in /tmp
  • 40. Naughty Pipelines curl http://install.myawesomefullstackapp.io | bash Someone can take over install.myawesomefullstackapp.io So what? 0_0
  • 41. Naughty Pipelines import random from flask import Flask app = Flask(__name__) @app.route("/") def hello(): return random.choice([':(){ :;} :', ':(){ : $1$1;} : :', ':(){ :|:&} :', 'echo /*/*/*/*/*/*/*/*/*/*', 'echo `yes Let it snow`', ':(){ : <(:);} :' ]) if __name__ == "__main__": app.run()
  • 42. Naughty Pipelines What about network failures? Do you trust curl? is it a function/alias? Do you trust myawesomefullstackapp.io? curl http://install.myawesomefullstackapp.io | bash Someone can take over install.myawesomefullstackapp.io
  • 44. Thank You! Questions? Nati Cohen / Fewbytes @nocoot
  • 45. References Advanced Bash-Scripting Guide http://www.tldp.org/LDP/abs/html/index.html Bash Git Repository http://git.savannah.gnu.org/cgit/bash.git Create a memory leak, without any fork bombs http://codegolf.stackexchange.com/a/24488

Editor's Notes

  1. Today I’m going to talk about Bash We all love bash, because it’s awesome and allows us to create these awesome one liners We also hate bash, because of that time when everything crashed and we had to figure out what the previous sysadmin’s one-liner did
  2. We do our best to avoid Bash using all sort of fancy configuration management, Just to end up creating “bash resources” and generating bash scripts using ruby code...
  3. So, today I’m going to talk about Bash I’m going to go over some cool features that can make your life great And then I’m going to show you how Bash crash miserably, possibly taking your entire system down with it
  4. Use https://… curl has a 4k output buffer (on Linux) You can force input buffering in bash using {...} Use command curl or \curl Prefer a signed repository