General TC > Programming & Scripting - Unofficial
in a script, could I have the main body folowed by its functions at the botom?
Rich:
Hi GNUser
Well done, thank you. :)
GNUser:
Hi Rich. You're welcome. It's rare that the help flows in that direction :)
Hi nick65go. You're welcome. Glad I could help. Actually, here's a better example of CustomGreeting.sh that shows what's going on a bit more clearly:
--- Code: ---#!/bin/sh
main()
{
say_hi "$1"
say_bye "$2"
}
say_hi()
{
echo "hi $1"
}
say_bye()
{
echo "bye $1"
}
main "$@"
--- End code ---
--- Code: ---$ ./CustomGreeting.sh "John" "Mr. John Doe"
hi John
bye Mr. John Doe
--- End code ---
Happy Hacking!
mocore:
--- Code: ---#!/bin/sh
main()
{
say_hi "$1"
say_bye "$2"
}
say_hi()
{
echo "hi $1"
}
say_bye()
{
echo "bye $1"
}
for argx in "${@}" ; do
case $argx in
m|main) shift ; main "${@}" ; exit 0 ;;
# other args
*) return 0 ;;
esac ; done
# no args
[ $# -eq 0 ] && return 0 ;
--- End code ---
with the above addition ( worked out in this (messy) topic http://forum.tinycorelinux.net/index.php/topic,26133.msg167895.html )
its possible to source the script to access the functions within shell
which imho can be useful for testing / composing new functions / cases .
Rich:
Hi mocore
--- Quote from: mocore on March 05, 2023, 02:42:14 AM --- ... its possible to source the script to access the functions within shell ...
--- End quote ---
Do you mean the way you can call functions from /etc/init.d/tc-functions from the command line:
--- Code: ---tc@E310:~$ echo $MIRROR
tc@E310:~$ getMirror
tc@E310:~$ echo $MIRROR
http://repo.tinycorelinux.net/10.x/x86/tcz
tc@E310:~$
--- End code ---
Because it's sourced in ~/.ashrc:
--- Code: ---tc@E310:~$ head -n 4 .ashrc
# ~/.ashrc: Executed by SHells.
#
. /etc/init.d/tc-functions
if [ -n "$DISPLAY" ]
tc@E310:~$
--- End code ---
mocore:
@rich
>Do you mean the way you can call functions from /etc/init.d/tc-functions from the command line:
yes like that callable in shell via sourcing a script
but while also avoiding calling the "main" function when sourced
id thaught i had not added an example after posting so...
--- Code: ---# source & use functions in shell
. ./CustomGreeting.sh
say_hi foobar
# or
./CustomGreeting.sh main ; # call script and run the man function
--- End code ---
an example
replacing
> main "$@"
in https://git.savannah.gnu.org/cgit/guix.git/plain/etc/guix-install.sh
with
--- Code: --- for argx in "${@}" ; do
case $argx in
m|main) shift ; main "${@}" ; exit 0 ;;
# other args
*) return 0 ;;
esac ; done
# no args
[ $# -eq 0 ] && return 0 ;
--- End code ---
allows ". source" of the script without ruining main
then functions or function inputs or environment can be tested / altered / ect
Navigation
[0] Message Index
[#] Next page
[*] Previous page
Go to full version