Monday, April 29, 2024
8
rated 0 times [  8] [ 0]  / answers: 1 / hits: 11769  / 3 Years ago, fri, october 22, 2021, 9:27:09

I can define a function like:



myfunction () { ls -R "$1" ; }



And then



myfunction .



just works.



But if I do



echo "myfunction ." | sh
echo "myfunction ." | bash


the messages are:



sh: myfunction: not found  
bash: line 1: myfunction: command not found


Why? And how can I call a function that comes from a string if not by piping it to sh or bash?



I know there is this command source, but I am confused of when I should use source and when sh or bash. Also, I cannot pipe through source. To add to confusion, there is this command . that seems to have nothing to do with the "." that means "current directory".


More From » command-line

 Answers
1

A function definition only has an effect in the current instance of bash. When you write



echo "myfunction ." | bash


you run another instance of bash. You would need to define the function in that other instance.



If you have a string that contains a function name and arguments (quoted, if necessary), or more generally any string that contains some shell source code that you want to execute, use the eval builtin.



my_snippet='myfunction .'
eval "$my_snippet"


If you define functions in your .bashrc, they are only available in interactive shells, not in scripts.



The . command is (almost) equivalent to source, and has nothing to do with . meaning the current directory.


[#37896] Saturday, October 23, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cocal

Total Points: 236
Total Questions: 111
Total Answers: 123

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
cocal questions
Tue, Oct 12, 21, 20:46, 3 Years ago
Sat, Oct 8, 22, 04:23, 2 Years ago
Wed, Sep 14, 22, 22:38, 2 Years ago
Sun, Dec 18, 22, 02:24, 1 Year ago
Wed, Jun 29, 22, 17:31, 2 Years ago
;