General TC > Programming & Scripting - Unofficial
in a script, could I have the main body folowed by its functions at the botom?
Rich:
Hi mocore
You can source right from the command line.
A file containing some functions:
--- Code: ---tc@E310:~$ ls -l Sourcing
-rw-rw-r-- 1 tc staff 20 Mar 6 09:31 Sourcing
tc@E310:~$ cat Sourcing
xyzzy()
{
cal $1
}
Mem()
{
free "-mo"
}
Path()
{
echo $PATH
}
tc@E310:~$
--- End code ---
No shebang, not executable, no main, just 3 functions.
The commands work after we source the file:
--- Code: ---tc@E310:~$ xyzzy
sh: xyzzy: not found
tc@E310:~$ xyzzy apr
sh: xyzzy: not found
tc@E310:~$ Mem
sh: Mem: not found
tc@E310:~$ Path
sh: Path: not found
tc@E310:~$ . ./Sourcing
tc@E310:~$ xyzzy
March 2023
Su Mo Tu We Th Fr Sa
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
tc@E310:~$ xyzzy apr
April 2023
Su Mo Tu We Th Fr Sa
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30
tc@E310:~$ Mem
total used free shared buffers cached
Mem: 3028 1477 1551 0 82 574
Swap: 999 0 999
tc@E310:~$ Path
/home/tc/.local/bin:/usr/local/sbin:/usr/local/bin:/apps/bin:/usr/sbin:/usr/bin:/sbin:/bin:/etc/sysconfig/tcedir/ondemand
tc@E310:~$
--- End code ---
mocore:
hi @rich
wrt title : in a script, could I have the main body folowed by its functions at the botom?
you can order functions in the script however you like
the order the of the named blocks in the script should not affect the script execution
unless a function is called before its defined
which will result in error
--- Code: ---$script: line $X: $funcname: not found
--- End code ---
as mentioned : https://forum.tinycorelinux.net/index.php/topic,26125.msg167737.html#msg167737
the example
adding an optional explicit case to call the main function then exit
and two return cases , one for no arguments and , one for all other args
allows changing script execution path making calling the main function optional
so other functions can be sourced into shell or other scripts
perhaps its considered better to have ?? ( that seams to be the gist of your reply )
lib-foo.sh
and
foo.sh
where foo.sh effectively encapsulates main block
and lib-foo.sh holds the functions to import
Navigation
[0] Message Index
[*] Previous page
Go to full version