How to solve the following error without defining `my_test` in `test.sh`?

```bash
my_test() {
echo test
}
echo my_test > test.sh
bash test.sh
```
```
test.sh: line 1: my_test: command not found
```
Jul 13, 12:34am

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.

Why it fails:

  • echo my_test > test.sh writes the literal string my_test to test.sh.
  • When bash test.sh runs, it tries to execute my_test as a command, but it doesn't exist in the new shell.

How to fix it without defining my_test in test.sh:

You need to export the function so it's available in the subshell. Use the export -f command:

bash
my_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).


Alternative (if you want to keep the function definition in the script):

If you want test.sh to define and use my_test, you'd need to write the function definition to the file, e.g.:

bash
echo '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.

Jul 13, 12:34am

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more