Functions (Bash)
Versie door Jeroen Strompf (overleg | bijdragen) op 4 sep 2021 om 13:28
Bash kent functies. Die lijken vaak beschouwd te worden als volwaardige implementaties van het concept van subroutines. Details:
- De functie moet eerst gedeclareerd worden, voordat je 'm kunt aanroepen. Maw. de functie-declaratie moet eerder in het script staan dan de aanroep
- Variabelen zijn standaard global - Handig: Daarmee zijn functies een hele aardige vervanging van subroutines, want tenminste gemakkelijk te debuggen.
Waarom functies?
Wat ik denk dat in het algemeen het nut van functies is:
- Clusteren van bij elkaar horende code
- Flow control, ihb. voorkomen van zich herhalende code
- Hergebruik: Rond m'n 13e leerde ik het concept van libraries en dat heeft me altijd aangesproken. De laatste jaren is mijn library (voornamelijk SQL-sprocs) daadwerkelijk een productiemiddel van me geworden, zij het van een beperkte grootte
- Abstractie: Op bepaalde momenten kun je je bezighouden met wat functies doen, zonder precies te hoeven weten hoe dat precies gedaan wordt.
Basis
[1]:
- POSIX-syntaxis voor functies:
fn_name () compound-command [ redirections ]
- Alternatieve Bash-syntaxis:
function fn_name [()] compound-command [ redirections ]
. - The exit status of a function definition is zero (success) unless another read-only function with a similar name already exists or a syntax error occurs
- Functies kunnen ook in direct mode in Bash toegepast worden.
Voorbeeld:
$ mijnfunctie() { echo "Hello, world!"; } $ mijnfunctie Hello, world!
[2]:
⚠️ When using the curly braces {} notation, make sure to separate the content of the function and the braces with blanks or newlines, otherwise, a syntax error near unexpected token will be raised. This is due to historical reasons as the braces are reserved words and can only be recognized as such when they are separated from the command list by whitespace or another shell metacharacter. Also when using the braces notation, you must terminate the last command by a semi-colon ;, an ampersand &, or a newline.
Bronnen
- https://ryanstutorials.net/bash-scripting-tutorial/bash-functions.php
- https://www.shell-tips.com/bash/functions/
- https://opensource.com/article/20/6/bash-functions
- https://linuxize.com/post/bash-functions
- https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-8.html
- https://tldp.org/LDP/abs/html/functions.html