Functions
Part of the Bash course
By now your scripts are starting to repeat themselves. Maybe you log a timestamped message in three different places, or you check whether a file exists before touching it, over and over, with the same three lines each time. Copying and pasting those lines works, until you need to fix a bug in them and discover you have to fix it in five places at once.
Think about a recipe card. You do not rewrite the steps for scrambled eggs every time you feel like eggs, you write the recipe once, put a name on the card, and from then on you just say "make the scrambled eggs" and everyone knows which steps you mean. A function is that recipe card for Bash: a block of commands, given a name, that you can run by writing the name instead of the commands themselves. ...
Want to learn Bash Functions in a real environment?
Click below, get a fresh Linux box with Bash ready to go, and work through Functions hands-on with an AI tutor that knows your code.
Start this lessonFunctionsWhat you'll learn
- Function definition
- Positional args $1 $@ $#
- Return for exit codes
- Echo for output
- Local variables
Read this lesson in your language
All lessons in this course
12 lessons- 1What Is Bash20 min
- 2Shebang and Your First Script25 min
- 3Variables and Quoting25 min
- 4Conditionals and Tests30 min
- 5Loops25 min
- 6Functions25 min
- 7Arrays25 min
- 8String and Arithmetic Expansion25 min
- 9IO Redirection and Pipes25 min
- 10Error Handling and Traps30 min
- 11Debugging and Best Practices25 min
- 12Capstone: Server Bootstrap Script60 min
