Bash Tutorial 5: Functions

preview_player
Показать описание
How to use Functions in Bash Script. Functions are a handy feature to use when your code starts getting a bit large. I cover how to parse variables into the function and how to get a return value (which isn't particularly straight forward in Bash compared to other programming languages).

In this tutorial I show how:
0:34 Create a Basic Function
1:00 Input Variables / Arguments into a Function
2:09 Return a value using error code
4:18 Return a value using a global variable

Рекомендации по теме
Комментарии
Автор

10 years ago! Holy shit i hope this is still relevant... it's bash so i know it is😅

JorgeEscobarMX
Автор

return and exit in Bash sets the exit status. return works in functions and scripts. exit works when Bash takes input from the keyboard.
When you ran the function, the exit status where set to 25. When you echoed it, echo printed out it and set the exit code to 0 (0 means that the program exited without any errors. When you echo the variable $? again, it'll be set to zero, because the last command did return the exit code 0..

Markus
Автор

I should also mention that functions doesn't create new subshells. The current environment and are affected. Functions are, though, faster then scripts. Scripts must be read before executing. Functions are already in the RAM.

Markus
Автор

It is used in exemples, just like the math is uing x and y's.
They have been used to name entities such as variables, functions, and commands whose purpose is unimportant and serve only to demonstrate a concept. The words themselves have no meaning in this usage.

Markus
Автор

hey man, can you make vids on ubuntu touch tutorials! :)

Videoorchard
Автор

It's not recommended to use return. Why? Because || and && won't work as you'll expect.

&& will only continue if the exit code is 0, and || will only continue if the exit status is NOT equal to 0.

This isn't just applying for Bash - it applies on all shells. Changing the exit status without knowing how exit statuses works and why they're useful is an bad idea. It's much better to use echo instead of return to return an variable.

Markus