Basisfuncties in Bash

Introductie tot Bash-scripting

Alex Scriven

Data Scientist

Waarom functies?

 

Als je functies in R of Python hebt gebruikt, ken je deze voordelen:

  1. Functies zijn herbruikbaar
  2. Functies maken nette, modulaire code mogelijk
  3. Functies helpen bij delen van code (je hoeft alleen input en output te weten)
Introductie tot Bash-scripting

Anatomie van een Bash-functie

Laten we de functiesyntaxis ontleden:

  • Begin met een naam. Die gebruik je om later aan te roepen.
    • Kies een logische naam.
  • Voeg haakjes na de functienaam toe
  • Zet de code tussen accolades. Je kunt alles gebruiken wat je al kent (loops, IF, shell-in-een-shell, etc.)
  • Optioneel iets retourneren (let op: dit werkt anders dan je denkt)

 

Een Bash-functie heeft deze syntax:

function_name () {
    #function_code
    return #something
}
Introductie tot Bash-scripting

Alternatieve Bash-functiestructuur

Je kunt ook zo een functie maken:

function function_name {
    #function_code
    return #something
}

Belangrijkste verschillen:

  • Gebruik het woord function om een functie te starten
  • Je kunt de haakjes op de eerste regel weglaten, al houden veel mensen ze aan uit gewoonte
Introductie tot Bash-scripting

Een Bash-functie aanroepen

Een Bash-functie aanroepen is simpelweg de naam schrijven:

function print_hello () {
    echo "Hello world!"
}

print_hello # hier roepen we de functie aan
Hello world!
Introductie tot Bash-scripting

Bash-functie: Fahrenheit naar Celsius

We schrijven een functie om Fahrenheit naar Celsius om te zetten, zoals eerder, met een statische variabele.

temp_f=30

function convert_temp () {
temp_c=$(echo "scale=2; ($temp_f - 32) * 5 / 9" | bc)
echo $temp_c }
convert_temp # functie aanroepen
-1.11
Introductie tot Bash-scripting

Laten we oefenen!

Introductie tot Bash-scripting

Preparing Video For Download...