Functions vs. scripts (Bash)

Uit De Vliegende Brigade
Naar navigatie springen Naar zoeken springen

How to not confuse functions with scripts when programming in Bash?

The problem

While programming in Bash, I often make calls to functions within the same file (e.g., backup_site, or to external scripts (e.g. source update_site.sh). Usually, external sites have an extention .sh, so it's easy to see that they are external files. But I don't do this always. In both cases, it's important that global variables (if that's the correct name) are preserved. How to keep track of whether someting is a function or an external script?

What would happen if a name is used by both?

How to keep track

Consistent Naming Conventions

  • Use a prefix for functions, e.g., fn_backup_site, fn_update_db
  • Use a .sh extension for external scripts, e.g., update_site.sh
  • Keep external scripts in a dedicated directory, e.g., scripts/

List Defined Functions

  • Use declare -F to check if a function exists:
  • To list all functions in the current session: declare -F

Check if a Name is an External Script

  • Use type to determine whether something is a function, alias, or external command:type backup_site

Explicitly Source External Scripts

Several ways to force the use of an external script:

  • source ./backup_site.sh
  • Include path. E.g.: ./backup_site.sh
  • bash backup_site.sh
  • Use command. E.g.: command backup_site.

Functions take precedence

If a function and an external script share the same name (e.g., backup_site), the function will be executed - not the file.