Redirecting output from a function block to a file in Linux - linux

Just like we redirect output from a for loop block to a file
for ()
do
//do something
//print logs
done >> output file
Similarly in shell script, is there a way to redirect output from a function block to a file, something like this?
function initialize {
//do something
//print something
} >> output file
//call initialize
If not, is there some other way I can achieve that? Please note my function has lot of messages to be printed in a log. Redirecting output to a file at every line would result in a lot of I/O utilization.

Do the redirection when you are calling the function.
#!/bin/bash
initialize() {
echo 'initializing'
...
}
#call the function with the redirection you want
initialize >> your_file.log
Alternatively, open a subshell in the function and redirect the subshell output:
#!/bin/bash
initialize() {
( # opening the subshell
echo 'initializing'
...
# closing and redirecting the subshell
) >> your_file.log
}
# call the function normally
initialize

The way you suggest is actually perfectly valid. The Bash manual gives the function declaration syntax as follows (emphasis mine)1:
Functions are declared using this syntax:
name () compound-command [ redirections ]
or
function name [()] compound-command [ redirections ]
So this would be perfectly valid and replace the contents of outfile with the argument to myfunc:
myfunc() {
printf '%s\n' "$1"
} > outfile
Or, to append to outfile:
myappendfunc() {
printf '%s\n' "$1"
} >> outfile
However, even though you can put the name of your target file into a variable and redirect to that, like this:
fname=outfile
myfunc() { printf '%s\n' "$1"; } > "$fname"
I think think it's much clearer to do the redirection where you call the function – just like recommended in other answers. I just wanted to point out that you can have the redirection as part of the function declaration.
1And this is not a bashism: the POSIX Shell spec also allows redirections in the function definition command.

You can use for exec for shell redirection not sure if it will work for functions
exec > output_file
function initialize {
...
}
initialize

My solution is wrap the function.
init_internal(){
echo "this is init_internal with params: $#"
echo "arg1 $1"
echo "arg2 $2"
}
init() {
local LOG_PATH=$1
echo "LOG at: $LOG_PATH"
init_internal "${#:2}" > ./$LOG_PATH 2>&1
}
init log.log a b c d
cat ./log.log
It outputs:
LOG at: log.log
this is init_internal with params: a b c d
arg1 a
arg2 b

Related

Changing global var inside function doesnt mutate global variable [duplicate]

I'm working with this:
GNU bash, version 4.1.2(1)-release (x86_64-redhat-linux-gnu)
I have a script like below:
#!/bin/bash
e=2
function test1() {
e=4
echo "hello"
}
test1
echo "$e"
Which returns:
hello
4
But if I assign the result of the function to a variable, the global variable e is not modified:
#!/bin/bash
e=2
function test1() {
e=4
echo "hello"
}
ret=$(test1)
echo "$ret"
echo "$e"
Returns:
hello
2
I've heard of the use of eval in this case, so I did this in test1:
eval 'e=4'
But the same result.
Could you explain me why it is not modified? How could I save the echo of the test1 function in ret and modify the global variable too?
When you use a command substitution (i.e., the $(...) construct), you are creating a subshell. Subshells inherit variables from their parent shells, but this only works one way: A subshell cannot modify the environment of its parent shell.
Your variable e is set within a subshell, but not the parent shell. There are two ways to pass values from a subshell to its parent. First, you can output something to stdout, then capture it with a command substitution:
myfunc() {
echo "Hello"
}
var="$(myfunc)"
echo "$var"
The above outputs:
Hello
For a numerical value in the range of 0 through 255, you can use return to pass the number as the exit status:
mysecondfunc() {
echo "Hello"
return 4
}
var="$(mysecondfunc)"
num_var=$?
echo "$var - num is $num_var"
This outputs:
Hello - num is 4
This needs bash 4.1 if you use {fd} or local -n.
The rest should work in bash 3.x I hope. I am not completely sure due to printf %q - this might be a bash 4 feature.
Summary
Your example can be modified as follows to archive the desired effect:
# Add following 4 lines:
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$#" "$?"; }
_capture() { { out="$("${#:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$#")"; }
e=2
# Add following line, called "Annotation"
function test1_() { passback e; }
function test1() {
e=4
echo "hello"
}
# Change following line to:
capture ret test1
echo "$ret"
echo "$e"
prints as desired:
hello
4
Note that this solution:
Works for e=1000, too.
Preserves $? if you need $?
The only bad sideffects are:
It needs a modern bash.
It forks quite more often.
It needs the annotation (named after your function, with an added _)
It sacrifices file descriptor 3.
You can change it to another FD if you need that.
In _capture just replace all occurances of 3 with another (higher) number.
The following (which is quite long, sorry for that) hopefully explains, how to adpot this recipe to other scripts, too.
The problem
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
d1=$(d)
d2=$(d)
d3=$(d)
d4=$(d)
echo $x $d1 $d2 $d3 $d4
outputs
0 20171129-123521 20171129-123521 20171129-123521 20171129-123521
while the wanted output is
4 20171129-123521 20171129-123521 20171129-123521 20171129-123521
The cause of the problem
Shell variables (or generally speaking, the environment) is passed from parental processes to child processes, but not vice versa.
If you do output capturing, this usually is run in a subshell, so passing back variables is difficult.
Some even tell you, that it is impossible to fix. This is wrong, but it is a long known difficult to solve problem.
There are several ways on how to solve it best, this depends on your needs.
Here is a step by step guide on how to do it.
Passing back variables into the parental shell
There is a way to pass back variables to a parental shell. However this is a dangerous path, because this uses eval. If done improperly, you risk many evil things. But if done properly, this is perfectly safe, provided that there is no bug in bash.
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; d=$(date +%Y%m%d-%H%M%S); _passback x d; }
x=0
eval `d`
d1=$d
eval `d`
d2=$d
eval `d`
d3=$d
eval `d`
d4=$d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-124945 20171129-124945 20171129-124945 20171129-124945
Note that this works for dangerous things, too:
danger() { danger="$*"; passback danger; }
eval `danger '; /bin/echo *'`
echo "$danger"
prints
; /bin/echo *
This is due to printf '%q', which quotes everything such, that you can re-use it in a shell context safely.
But this is a pain in the a..
This does not only look ugly, it also is much to type, so it is error prone. Just one single mistake and you are doomed, right?
Well, we are at shell level, so you can improve it. Just think about an interface you want to see, and then you can implement it.
Augment, how the shell processes things
Let's go a step back and think about some API which allows us to easily express, what we want to do.
Well, what do we want do do with the d() function?
We want to capture the output into a variable.
OK, then let's implement an API for exactly this:
# This needs a modern bash 4.3 (see "help declare" if "-n" is present,
# we get rid of it below anyway).
: capture VARIABLE command args..
capture()
{
local -n output="$1"
shift
output="$("$#")"
}
Now, instead of writing
d1=$(d)
we can write
capture d1 d
Well, this looks like we haven't changed much, as, again, the variables are not passed back from d into the parent shell, and we need to type a bit more.
However now we can throw the full power of the shell at it, as it is nicely wrapped in a function.
Think about an easy to reuse interface
A second thing is, that we want to be DRY (Don't Repeat Yourself).
So we definitively do not want to type something like
x=0
capture1 x d1 d
capture1 x d2 d
capture1 x d3 d
capture1 x d4 d
echo $x $d1 $d2 $d3 $d4
The x here is not only redundant, it's error prone to always repeate in the correct context. What if you use it 1000 times in a script and then add a variable? You definitively do not want to alter all the 1000 locations where a call to d is involved.
So leave the x away, so we can write:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
d() { let x++; output=$(date +%Y%m%d-%H%M%S); _passback output x; }
xcapture() { local -n output="$1"; eval "$("${#:2}")"; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
This already looks very good. (But there still is the local -n which does not work in oder common bash 3.x)
Avoid changing d()
The last solution has some big flaws:
d() needs to be altered
It needs to use some internal details of xcapture to pass the output.
Note that this shadows (burns) one variable named output,
so we can never pass this one back.
It needs to cooperate with _passback
Can we get rid of this, too?
Of course, we can! We are in a shell, so there is everything we need to get this done.
If you look a bit closer to the call to eval you can see, that we have 100% control at this location. "Inside" the eval we are in a subshell,
so we can do everything we want without fear of doing something bad to the parental shell.
Yeah, nice, so let's add another wrapper, now directly inside the eval:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
# !DO NOT USE!
_xcapture() { "${#:2}" > >(printf "%q=%q;" "$1" "$(cat)"); _passback x; } # !DO NOT USE!
# !DO NOT USE!
xcapture() { eval "$(_xcapture "$#")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
prints
4 20171129-132414 20171129-132414 20171129-132414 20171129-132414
However, this, again, has some major drawback:
The !DO NOT USE! markers are there,
because there is a very bad race condition in this,
which you cannot see easily:
The >(printf ..) is a background job. So it might still
execute while the _passback x is running.
You can see this yourself if you add a sleep 1; before printf or _passback.
_xcapture a d; echo then outputs x or a first, respectively.
The _passback x should not be part of _xcapture,
because this makes it difficult to reuse that recipe.
Also we have some unneded fork here (the $(cat)),
but as this solution is !DO NOT USE! I took the shortest route.
However, this shows, that we can do it, without modification to d() (and without local -n)!
Please note that we not neccessarily need _xcapture at all,
as we could have written everyting right in the eval.
However doing this usually isn't very readable.
And if you come back to your script in a few years,
you probably want to be able to read it again without much trouble.
Fix the race
Now let's fix the race condition.
The trick could be to wait until printf has closed it's STDOUT, and then output x.
There are many ways to archive this:
You cannot use shell pipes, because pipes run in different processes.
One can use temporary files,
or something like a lock file or a fifo. This allows to wait for the lock or fifo,
or different channels, to output the information, and then assemble the output in some correct sequence.
Following the last path could look like (note that it does the printf last because this works better here):
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_xcapture() { { printf "%q=%q;" "$1" "$("${#:2}" 3<&-; _passback x >&3)"; } 3>&1; }
xcapture() { eval "$(_xcapture "$#")"; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
xcapture d1 d
xcapture d2 d
xcapture d3 d
xcapture d4 d
echo $x $d1 $d2 $d3 $d4
outputs
4 20171129-144845 20171129-144845 20171129-144845 20171129-144845
Why is this correct?
_passback x directly talks to STDOUT.
However, as STDOUT needs to be captured in the inner command,
we first "save" it into FD3 (you can use others, of course) with '3>&1'
and then reuse it with >&3.
The $("${#:2}" 3<&-; _passback x >&3) finishes after the _passback,
when the subshell closes STDOUT.
So the printf cannot happen before the _passback,
regardless how long _passback takes.
Note that the printf command is not executed before the complete
commandline is assembled, so we cannot see artefacts from printf,
independently how printf is implemented.
Hence first _passback executes, then the printf.
This resolves the race, sacrificing one fixed file descriptor 3.
You can, of course, choose another file descriptor in the case,
that FD3 is not free in your shellscript.
Please also note the 3<&- which protects FD3 to be passed to the function.
Make it more generic
_capture contains parts, which belong to d(), which is bad,
from a reusability perspective. How to solve this?
Well, do it the desparate way by introducing one more thing,
an additional function, which must return the right things,
which is named after the original function with _ attached.
This function is called after the real function, and can augment things.
This way, this can be read as some annotation, so it is very readable:
_passback() { while [ 0 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; }
_capture() { { printf "%q=%q;" "$1" "$("${#:2}" 3<&-; "$2_" >&3)"; } 3>&1; }
capture() { eval "$(_capture "$#")"; }
d_() { _passback x; }
d() { let x++; date +%Y%m%d-%H%M%S; }
x=0
capture d1 d
capture d2 d
capture d3 d
capture d4 d
echo $x $d1 $d2 $d3 $d4
still prints
4 20171129-151954 20171129-151954 20171129-151954 20171129-151954
Allow access to the return-code
There is only on bit missing:
v=$(fn) sets $? to what fn returned. So you probably want this, too.
It needs some bigger tweaking, though:
# This is all the interface you need.
# Remember, that this burns FD=3!
_passback() { while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
passback() { _passback "$#" "$?"; }
_capture() { { out="$("${#:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)"; }
capture() { eval "$(_capture "$#")"; }
# Here is your function, annotated with which sideffects it has.
fails_() { passback x y; }
fails() { x=$1; y=69; echo FAIL; return 23; }
# And now the code which uses it all
x=0
y=0
capture wtf fails 42
echo $? $x $y $wtf
prints
23 42 69 FAIL
There is still a lot room for improvement
_passback() can be elmininated with passback() { set -- "$#" "$?"; while [ 1 -lt $# ]; do printf '%q=%q;' "$1" "${!1}"; shift; done; return $1; }
_capture() can be eliminated with capture() { eval "$({ out="$("${#:2}" 3<&-; "$2_" >&3)"; ret=$?; printf "%q=%q;" "$1" "$out"; } 3>&1; echo "(exit $ret)")"; }
The solution pollutes a file descriptor (here 3) by using it internally.
You need to keep that in mind if you happen to pass FDs.
Note thatbash 4.1 and above has {fd} to use some unused FD.
(Perhaps I will add a solution here when I come around.)
Note that this is why I use to put it in separate functions like _capture, because stuffing this all into one line is possible, but makes it increasingly harder to read and understand
Perhaps you want to capture STDERR of the called function, too.
Or you want to even pass in and out more than one filedescriptor
from and to variables.
I have no solution yet, however here is a way to catch more than one FD, so we can probably pass back the variables this way, too.
Also do not forget:
This must call a shell function, not an external command.
There is no easy way to pass environment variables out of external commands.
(With LD_PRELOAD= it should be possible, though!)
But this then is something completely different.
Last words
This is not the only possible solution. It is one example to a solution.
As always you have many ways to express things in the shell.
So feel free to improve and find something better.
The solution presented here is quite far from being perfect:
It was nearly not tested at all, so please forgive typos.
There is a lot of room for improvement, see above.
It uses many features from modern bash, so probably is hard to port to other shells.
And there might be some quirks I haven't thought about.
However I think it is quite easy to use:
Add just 4 lines of "library".
Add just 1 line of "annotation" for your shell function.
Sacrifices just one file descriptor temporarily.
And each step should be easy to understand even years later.
Maybe you can use a file, write to file inside function, read from file after it. I have changed e to an array. In this example blanks are used as separator when reading back the array.
#!/bin/bash
declare -a e
e[0]="first"
e[1]="secondddd"
function test1 () {
e[2]="third"
e[1]="second"
echo "${e[#]}" > /tmp/tempout
echo hi
}
ret=$(test1)
echo "$ret"
read -r -a e < /tmp/tempout
echo "${e[#]}"
echo "${e[0]}"
echo "${e[1]}"
echo "${e[2]}"
Output:
hi
first second third
first
second
third
What you are doing, you are executing test1
$(test1)
in a sub-shell( child shell ) and Child shells cannot modify anything in parent.
You can find it in bash manual
Please Check: Things results in a subshell here
I had a similar problem when I wanted to remove temporary files I had created automatically. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.
#!/usr/bin/env bash
# array that keeps track of tmp-files
remove_later=()
# function that manages tmp-files
new_tmp_file() {
file=$(mktemp)
remove_later+=( "$file" )
# assign value (safe form of `eval "$1=$file"`)
printf -v "$1" -- "$file"
}
# function to remove all tmp-files
remove_tmp_files() { rm -- "${remove_later[#]}"; }
# define trap to remove all tmp-files upon EXIT
trap remove_tmp_files EXIT
# generate tmp-files
new_tmp_file tmpfile1
new_tmp_file tmpfile2
So, adapting this to the OP, it would be:
#!/usr/bin/env bash
e=2
function test1() {
e=4
printf -v "$1" -- "hello"
}
test1 ret
echo "$ret"
echo "$e"
Works and has no restrictions on the "return value".
Assuming that local -n is available, the following script lets the function test1 modify a global variable:
#!/bin/bash
e=2
function test1() {
local -n var=$1
var=4
echo "hello"
}
test1 e
echo "$e"
Which gives the following output:
hello
4
I'm not sure if this works on your terminal, but I found out that if you don't provide any outputs whatsoever it gets naturally treated as a void function, and can make global variable changes.
Here's the code I used:
let ran1=$(( (1<<63)-1)/3 ))
let ran2=$(( (1<<63)-1)/5 ))
let c=0
function randomize {
c=$(( ran1+ran2 ))
ran2=$ran1
ran1=$c
c=$(( c > 0 ))
}
It's a simple randomizer for games that effectively modifies the needed variables.
It's because command substitution is performed in a subshell, so while the subshell inherits the variables, changes to them are lost when the subshell ends.
Reference:
Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment
A solution to this problem, without having to introduce complex functions and heavily modify the original one, is to store the value in a temporary file and read / write it when needed.
This approach helped me greatly when I had to mock a bash function called multiple times in a bats test case.
For example, you could have:
# Usage read_value path_to_tmp_file
function read_value {
cat "${1}"
}
# Usage: set_value path_to_tmp_file the_value
function set_value {
echo "${2}" > "${1}"
}
#----
# Original code:
function test1() {
e=4
set_value "${tmp_file}" "${e}"
echo "hello"
}
# Create the temp file
# Note that tmp_file is available in test1 as well
tmp_file=$(mktemp)
# Your logic
e=2
# Store the value
set_value "${tmp_file}" "${e}"
# Run test1
test1
# Read the value modified by test1
e=$(read_value "${tmp_file}")
echo "$e"
The drawback is that you might need multiple temp files for different variables. And also you might need to issue a sync command to persist the contents on the disk between one write and read operations.
You can always use an alias:
alias next='printf "blah_%02d" $count;count=$((count+1))'

Parameter substitution in a string bash

In my shell script, I had defined few messages that I need to log as INFO, WARN or ERROR.
The messages are as follows:
###### This may not be correct syntax as I need to know this #######
BACKUP_INFO="File {} is compressed at path {}."
ERROR_FILE_NOT_EXIST="File {} doesn\'t exist."
OTHER_ERROR="Cannot backup File {}, Reason: {}"
I have a methods to log this information in a file:
function print_info() {
echo -e "$(date +'%F %T') ${SCRIPTNAME}: INFO: ${*}" | tee -a ${LOGFILE};
}
Now I need to pass my messages to method print info in such a way that the first parameter should be placed at first {}, second parameter should be placed at second {}, and so on.
Even I tried to declare my message as
BACKUP_INFO="File $FILE_NAME is compressed at path $BACKUP_DIR."
But the problem is the variables FILE_NAME and BACKUP_DIR are inside a method, and the message is defined globally.
Somewhat I want to use it as shown below:
print_info $BACKUP_INFO $FILE_NAME $FILE_PATH
so that the output should come as
2015-03-13 07:05:05 : INFO: File /opt/mgtservices/relay.log is compressed at path /root/backup
I need to know the correct syntax how I can achieve this.
You could use printf for that, using "%s" for the placeholder.
Here's an example:
SCRIPT_NAME="foo.sh"
FORMAT="hello %s, %s"
print_info() {
format="$1"
shift
printf "$(date +%F) $SCRIPT_NAME: $format\n" "$#"
}
name="bob"
message="how are you?"
print_info "$FORMAT" "$name" "$message"
Since the parameters are context dependent anyway, it doesn't really make much sense to abstract these to the point where you have the message strings in global variables. Whichever function needs to print BACKUP_INFO also needs to know what placeholders there are in the string, so it might as well include the string directly. If you don't want that, maybe change them into functions, too.
print_info () {
local fmt
fmt=$1
shift
printf "$(date +'%F %T') ${SCRIPTNAME}: INFO: $fmt\n" "$#" | tee -a "$LOGFILE"
}
backup_info () { print_info 'File %s is compressed at path %s.' "$1" "$2"; }
error_file_not_exist () { print_info "File %s doesn't exist." "$1"; }
# XXX FIXME: "other_error" is really a misnomer!
other_error () { print_info 'Cannot backup File %s, Reason: %s' "$1" "$2"; }
Somewhat coincidentally, this might actually also offer some benefits if you want to provide localization support for your script; then if the word order of the English strings are wrong for a target language, the translator can override the English formatting function with a different one.

Bash get output from class

I've got a script, and I want to do something like this :
text1() {
something here
}
show(){
echo test1()
and some text here
}
Basically I want to use output from the first class function in the second class function, how I can do this?
If you want to put to a variable a value that function returns to stdout, use $():
foo() {
printf '%s\n' 'ququ'
}
bar() {
VAR="$(foo)"
echo "$VAR"
}
I. e. functions in GNU Bash (and other shells as well) are like external utilities.
I don't know if this is really what you want, but ...
You must know that bash functions, internal commands and standard tools don't return their output. Instead they write it on stdout. When you don't use any redirection, stdout is the terminal screen where you launched the command.
function text1() {
echo "In text1()"
}
function show(){
test1
echo "In show()"
}
If I call text1 from my terminal:
sh$ text1
In text1()
The function text1 during its execution invokes echo that send output to stdout. I see the result on the console.
sh$ show
In text1()
In show()
Calling show executes text1 (producing the same output as previously) followed by the output of the second echo.
If you want to store in a variable the intermediate result of a function or command, you might use the VAR=$( ...) notation. Think of that like "capturing" the output:
function text1() {
echo "In text1()"
}
function show(){
MYVAR=$(text1)
echo "In show() where MYVAR = ${MYVAR}"
}
Please compare the output now, with the previous case:
sh$ show
In show() where MYVAR = In text1()

How to return data from a bash shell script subroutine?

Given the following two executable scripts:
----- file1.sh
#!/bin/sh
. file2.sh
some_routine data
----- file2.sh
#!/bin/sh
some_routine()
{
#get the data passed in
localVar=$1
}
I can pass 'data' to a subroutine in another script, but I would also like to return data.
Is it possible to return information from some_routine?
e.g: var = some_routine data
Have the subroutine output something, and then use $() to capture the output:
some_routine() {
echo "foo $1"
}
some_var=$(some_routine bar)
It's not allowed, just set the value of a global variable (..all variables are global in bash)
if
some_routine() {
echo "first"
echo "foo $1"
}
some_var=$(some_routine "second")
echo "result: $some_var"
they are ok.But the result seems to be decided by the first "echo".Another way is use "eval".
some_var return "first"
some_routine()
{
echo "cmj"
eval $2=$1
}
some_routine "second" some_var
echo "result: $some_var"
in this way, some_var return "second".The bash don't return a string directly.So we need some tricks.

Get a list of function names in a shell script [duplicate]

This question already has answers here:
How do I list the functions defined in my shell? [duplicate]
(8 answers)
Closed 4 years ago.
I have a Bourne Shell script that has several functions in it, and allows to be called in the following way:
my.sh <func_name> <param1> <param2>
Inside, func_name() will be called with param1 and param2.
I want to create a help function that would just list all available functions, even without parameters.
The question: how do I get a list of all function names in a script from inside the script?
I'd like to avoid having to parse it and look for function patterns. Too easy to get wrong.
Update: the code. Wanted my help() function be like main() - a function added to the code is added to the help automatically.
#!/bin/sh
# must work with "set -e"
foo ()
{
echo foo: -$1-$2-$3-
return 0
}
# only runs if there are parameters
# exits
main ()
{
local cmd="$1"
shift
local rc=0
$cmd "$#" || rc=$?
exit $rc
}
if [[ "$*" ]]
then
main "$#"
die "how did we get here?"
fi
You can get a list of functions in your script by using the grep command on your own script. In order for this approach to work, you will need to structure your functions a certain way so grep can find them. Here is a sample:
$ cat my.sh
#!/bin/sh
function func1() # Short description
{
echo func1 parameters: $1 $2
}
function func2() # Short description
{
echo func2 parameters: $1 $2
}
function help() # Show a list of functions
{
grep "^function" $0
}
if [ "_$1" = "_" ]; then
help
else
"$#"
fi
Here is an interactive demo:
$ my.sh
function func1() # Short description
function func2() # Short description
function help() # Show a list of functions
$ my.sh help
function func1() # Short description
function func2() # Short description
function help() # Show a list of functions
$ my.sh func1 a b
func1 parameters: a b
$ my.sh func2 x y
func2 parameters: x y
If you have "private" function that you don't want to show up in the help, then omit the "function" part:
my_private_function()
{
# Do something
}
typeset -f returns the functions with their bodies, so a simple awk script is used to pluck out the function names
f1 () { :; }
f2 () { :; }
f3 () { :; }
f4 () { :; }
help () {
echo "functions available:"
typeset -f | awk '/ \(\) $/ && !/^main / {print $1}'
}
main () { help; }
main
This script outputs:
functions available:
f1
f2
f3
f4
help
You call this function with no
arguments and it spits out a
"whitespace" separated list of
function names only.
function script.functions () {
local fncs=`declare -F -p | cut -d " " -f 3`; # Get function list
echo $fncs; # not quoted here to create shell "argument list" of funcs.
}
To load the functions into an array:
declare MyVar=($(script.functions));
Of course, common sense dictates that
any functions that haven't been
sourced into the current file before
this is called will not show up in the
list.
To Make the list read-only and
available for export to other scripts
called by this script:
declare -rx MyVar=($(script.functions));
To print the entire list as newline
separated:
printf "%s\n" "${MyVar[#]}";
The best thing to do is make an array (you are using bash) that contains functions that you want to advertise and have your help function iterate over and print them.
Calling set alone will produce the functions, but in their entirety. You'd still have to parse that looking for things ending in () to get the proverbial symbols.
Its also probably saner to use something like getopt to turn --function-name into function_name with arguments. But, well, sane is relative and you have not posted code :)
Your other option is to create a loadable for bash (a fork of set) that accomplishes this. Honestly, I'd prefer going with parsing before writing a loadable for this task.

Resources