General TC > Programming & Scripting - Unofficial
in a script, could I have the main body folowed by its functions at the botom?
nick65go:
Hi, sorry for maybe a novice question.
I would like to typically define the main logic prior to defining its inner sub-functions, so someone reading the code will focus on the main logic first. Often this takes the form of creating a "main" function at the top of the file, and invoking it at the bottom. I mean just write code from top-to-bottom, sprinkling in functions as needed at the bottom, after main code/function exit?
Is there any lost speed in sh-type scripts like these? Or any memory issues not-initialized variables?
curaga:
Should be fine to write like that.
Rich:
Hi nick65go
I think I tried something similar but received errors because I was
trying to call functions before they were defined. You can get
around this by sourcing a file containing your functions at the
top of your script.
GNUser:
Hi, nick65go and Rich. Sure it's possible to define a main function at the top of a shell script followed by ancillary functions!
The shell reads shell scripts from top to bottom. If you call the main function at the bottom of the script, at that point the shell will have seen all the function definitions. Try this trivial example--call it HardcodedGreetings.sh:
--- Code: ---#!/bin/sh
main()
{
say_hi
say_bye
}
say_hi()
{
echo "hi"
}
say_bye()
{
echo "bye"
}
main
--- End code ---
The script works exactly as expected:
--- Code: ---$ ./HardcodedGreetings.sh
hi
bye
--- End code ---
If the script has arguments, you need to remember to pass the script's arguments to the main function. Here is a trivial example to illustrate this--let's call this one CustomGreeting.sh:
--- Code: ---#!/bin/sh
main()
{
say_arguments "$@"
}
say_arguments()
{
echo "$@"
}
main "$@"
--- End code ---
Again, it works exactly as expected:
--- Code: ---$ ./CustomGreeting.sh testing 1 2 3
testing 1 2 3
--- End code ---
nick65go:
@GNUser: Thanks, very good that you gave the examples. Also good that there is no penalty in execution speed.
Navigation
[0] Message Index
[#] Next page
Go to full version