The error occurs because my_test is defined as a shell function in your current shell session, but when you run bash test.sh, it starts a new shell process where my_test is not defined.
echo my_test > test.sh writes the literal string my_test to test.sh.bash test.sh runs, it tries to execute my_test as a command, but it doesn't exist in the new shell.my_test in test.sh:You need to export the function so it's available in the subshell. Use the export -f command:
bashmy_test() { echo test } export -f my_test echo my_test > test.sh bash test.sh
This will work because export -f my_test makes the function available to child processes (like the new bash instance running test.sh).
If you want test.sh to define and use my_test, you'd need to write the function definition to the file, e.g.:
bashecho 'my_test() { echo test; }; my_test' > test.sh bash test.sh
But since you asked for a solution without defining my_test in test.sh, the export -f approach is the way to go.
Vibe can make mistakes. Check answers. Learn more