How can I define a function as an element of an array?
I know I can do this:
function array[5](){ echo "you are inside the function"; }
And it is a valid function, in the sense that, the instruction array[5], correctly execute the function.
Unlucky, the function is not listed in the keys of the array, so, echo ${!array[*]} does not return 5 as a key.
For instance, the following code:
array[0]="first"
function array[5](){ echo "you are inside the function"; }
array[7]="seventh"
echo ${!array[*]}
Only returns 0 7.
So, how can I add a function to an array element, so that I can loop over it?
You can't really put the function itself in the array. But what you can do is put the function name in that field. Look:
a_pretty_function() {
echo "you're inside a function";
}
array[5]=a_pretty_function
# Execute it:
"${array[5]}"
When you're doing
array[5]() { echo "you are inside the function"; }
you're defining a function called array[5] as you can check with declare -pf array[5].
With this mechanism you can do something horribly ugly:
array[5]() { echo "you are inside the function"; }
i=5
"array[$i]"
and this will execute the function array[5]. I wouldn't recommend such a practice in any case.
Related
myfunc3()
{
echo $1
}
myfunc2()
{
input=$(myfunc3 10)
echo "someting that will be used later"
}
myfunc1() {
var=$(myfunc2) #this does not update the value
# myfunc2 This updates the value
}
input="$(myfunc3 1)"
echo "The new value is: $input"
myfunc1
echo "The new value is: $input"
I have 3 functions that are interrelated. I am trying to update the value of the input variable. I am able to do it when I simply call the function myfunc2 but when I am trying to get the returned value like var=$(myfunc2) as I want to use it for further uses, then the value of the input variable is not updating.
I am very new to shell scripting and I'm not able to understand the reasoning behind it.
Is there any other way to return the value or calling the function?
Thanks in advance
I'm trying to store a value returned from a method like this: var=$(methodName), but the program never enters the method... It's weird because I do the same thing a few lines earlier (alreadyExists-variable in code sample), and it works fine. I had to do this: var='methodName' to make the program enter the method.
It works, so why care? I'm probably making a mistake, and I need to know what it is and learn from it. Let me know if you need more info to answer the question. Thanks!
overwriteOrNot()
{
echo DEBUG
# This debug string does not print if method is called from "local overwrite=$(overwriteOrNot)"
# but prints if method is called from "local overwrite='overwriteOrNot'"
...
}
local alreadyExists=$(studentNumberExists studentNumber)
if $alreadyExists ; then
# local overwrite=$(overwriteOrNot)
local overwrite='overwriteOrNot'
...
If you're using return, then you need to either directly branch on its result:
if overwriteOrNot; then
: "the function returned 0"
else
: "the function returned something other than 0"
fi
...or store the value of $? immediately after running the function:
overwriteOrNot
local overwrite=$?
Note that return can only return a single-byte integer. If you need to pass content which doesn't fit that type, it needs to be either passed on stdout or in a global variable.
The following:
local overwrite='overwriteOrNot'
assigns a string; it doesn't invoke a function. Instead:
local overwrite=$(overwriteOrNot)
You can check the return value from calling overwriteOrNot with the $? variable, or by checking its numeric return value directly in a conditional statement like:
if overwriteOrNot; then
:
fi
If you assign to overwrite, you can also check its value with any valid test condition such as equality, regular expression match, or emptiness. For example:
if [[ "$overwrite" == "foo" ]]; then
:
fi
I'm not really sure a good name for this question so please rename it if you can think of a better one.
In Bash I have a function that I am using to store certain functions. Consider:
menv_funcs=()
function menv_function {
menv_funcs+=($1)
}
I am then using it in this manner:
menv_function fetch
function fetch {
...
}
I would like to use it like this though:
menv_function fetch {
...
}
Essentially I'm looking for something like the preprocessor macros in C would do but I have been unable to find a way. Any ideas?
As far as I'm aware, you can't directly achieve this. However, I can think of two solutions that may be of interest to you.
First of all, you could just declare the functions as usual, and then obtain the list of declared functions through declare -F. This could be done like:
function fetch {
:
}
menv_funcs=()
while IFS=$"\n" read l; do
menv_funcs+=${l#declare -f }
done < <(declare -F)
Which will cause menv_funcs[#] to list all the functions declared at the point of calling the snippet. Of course, this may catch unwanted functions as well.
To avoid this, you may add some prefix to function names and filter the list:
function menv_fetch {
:
}
menv_funcs=()
while IFS=$"\n" read l; do
if [[ ${l} == 'declare -f menv_'* ]]; then
menv_funcs+=${l#declare -f menv_}
fi
done < <(declare -F)
And if you really want to achieve something like macros, you may try to play with eval:
menv_funcs=()
function menv_function {
local name=${1}
local body=${2}
menv_funcs+=( ${name} )
eval "function ${name} ${body}"
}
menv_function fetch "{
:
}"
But note that you will actually need to quote the whole function body and escape everything appropriately.
If I have a very simple script that contains a function that just does the following:
function saySomething() {
Write-Output "Saying someting..."
}
If I call this function from the console the output is displayed. If I, however, do the following:
$something = saySomething
Then no output is displayed. Obviously my working example is much more complicated than this, but in short, how do I display the output within a function if that function is used to set a variable?
Try the following:
saySomething | Tee-Object -Variable something
This should work exactly as you want.
Is there a way to make a bash alias (or function) with its name coming from a variable?
For instance, is it possible to do something along these lines:
create_alias_with_name() {
alias $1="echo a custom alias"
}
Or something along these lines:
create_func_with_name() {
$1() {
"echo inside a function with a variable name"
}
}
In other words, I would prefer to have some kind of function "factory" that can register functions for me. Is this possible or beyond the capabilities of Bash?
Did you even try it? Your first example works fine.
You can make the second work by adding an eval:
create_func_with_name() {
eval "$1() {
echo inside a function with a variable name
}"
}
just in case, one may use a variable both as a part of the alias name and as a part of the alias command:
alias foo${var1}="bar${var2}"