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.
If you define these in your ~/.bash_aliases
file, which is an Ubuntu-specific thing and gets sourced by ~/.bashrc
in a default Ubuntu install, then yes, there is an overhead since the file will be sourced each time you start a new interactive, non-login shell. So each time you open a new terminal window, for example. Now, with modern machines, this overhead will most likely be undetectable, but it can be an issue for older machines, embedded systems or if you start having loads of complex functions defined.
In addition, functions and aliases defined this way are not accessible to scripts by default. So if you want to use one of those functions in your scripts, you will need to source .bashrc
(or .bash_aliases
) explicitly. If you have them as external script files in your $PATH
, that won't be needed.
My personal rule of thumb comes down to the complexity of the commands involved and whether or not the function/script I am writing is likely to be useful to non-interactive shells (e.g. other scripts). If I find myself writing several dozen lines of code, then I'll likely move it to a script. If I'm writing something that can be used in many different contexts and can likely come in handy when writing another script then, again, I'll move it to a script.
If, however, I just want a simple little function like the one you show in your question, that's only really useful when run interactively, then I'll stick to functions. So it really is a matter of your own personal preference and considering how and when you will want to use the functions you are defining.
Best Answer
Because you already have single quotes in the string, use double quotes, and escape only the
$
sign: