Functions (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

Bash kent functies. Die lijken vaak beschouwd te worden als volwaardige implementaties van het concept van subroutines.

Eerst declareren

Een functie moet eerst gedeclareerd worden, voordat je 'm kunt aanroepen. Maw. de functie-declaratie moet eerder in het script staan dan de aanroep.

Zijn variabelen global?

Ik dacht dat variabelen standaard global zijn en daarmee zouden functies een aardige vervanging van subroutines kunnen zijn, want te debuggen. In juni 2022 leek dit toch anders te liggen: Een associate array gedefineerd binnen een functie, bleek buiten die functie niet beschikbaar te zijn.

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