is there a way to export a function to another function?
i'm using
#!/usr/xpg4/bin/sh
in the first line of my script.
firstfunc () {
echo $1 is nice
}
secondfunc () {
firstfunc Nancy
}
when i run a similar scenario to the above, i get:
/usr/xpg4/bin/sh[4]: firstfunc: not found
Hello SkySmart,
I haven't tested this in Sun/Solaris box but I think you have to call the second function at last to execute it. So following you could try and let us know how it goes then.
firstfunc () {
echo $1 is nice
}
secondfunc () {
firstfunc Nancy
}
secondfunc
NOTE: I have tested above in BASH and worked fine for me.
Thanks,
R. Singh
i should elaborate. i'm runningg it a in a bit of an unusual way:
#!/bin/sh
1:
2:firstfunc () {
3:echo $1 is nice
4:}
5:
6:secondfunc () {
7:firstfunc Nancy
8:}
9: secondfunc
sed -n 6,9p $0 | sh
i know its very strange how i'm running it, but i have my reasons for do it this way.
somehow, it apperas when i run the sed command to self read the running script, the shell doesn't recognize the already defined function.
i'm really hoping to be able to get around this.
Hello SkySmart,
I am sorry but it is still not clear what you want to do, if you want to create some functions and call them according to number then you could use switch case. Now coming to your requirement in case you wanted to print lines from 6th to 9th then you should mention sed outside of the Input_file as follows.
cat Input_file
#!/bin/sh
1:
2:firstfunc () {
3:echo $1 is nice
4:}
5:
6:secondfunc () {
7:firstfunc Nancy
8:}
9: secondfunc
sed -n 6,9p Input_file
I have removed | sh in command sed -n 6,9p Input_file as you wanted to simply print lines. As I have mentioned before in case you wanted to execute some commands which you are printing from sed and wanted to execute you could use | sh then.
Now in case you wanted to use sed within your script itself then you could do following with the use of EOF .
cat script.ksh
cat << EOF > Input_file
#!/bin/sh
1:
2:firstfunc () {
3:echo $1 is nice
4:}
5:
6:secondfunc () {
7:firstfunc Nancy
8:}
9: secondfunc
EOF
sed -n 6,9p Input_file
If above both solutions are not matching your requirement, request you to be more precise in your requirement and provide us all the inputs from your side, I hope this helps.
Thanks,
R. Singh
When I run :
sed -n 6,9p testscript
(assuming that the numbers in your script are not there in real life) I get:
<empty line>
secondfunc () {
firstfunc Nancy
}
So these are the four lines of your code that get piped into a new Bourne shell (sh), which is like a new script and in that script firstfunc() is not defined.
--
Also note:
In your second example you are not using:
#!/usr/xpg4/bin/sh but #!/bin/sh . And you are feeding the output into a new (Bourne, not Posix) shell. To use a posix shell you either have to export your path to /usr/xpg4/bin:$PATH or pipe your output to /usr/xpg4/bin/sh rather than sh