1

I am new to shell script and recently wrote a script to open a new terminal window and run defined functions via osascript with "do shell script", but the result showed the command not found. My script is as below:

#!/bin/bash

hello() {
    echo "Hello World"
}

openNewWindowAndRun() {
    osascript -e "
        tell application \"Terminal\"
            activate        
            do script \"$1\"
        end tell
    "
}

openNewWindowAndRun hello

I have also tried to directly call the hello function in the openNewWindowAndRun but didn't get any luck:

#!/bin/bash

hello() {
    echo "Hello World"
}

openNewWindowAndRun() {
    osascript -e "
        tell application \"Terminal\"
            activate        
            do script \"hello\"
        end tell
    "
}

openNewWindowAndRun

When I ran the script, it opened the new window successfully but showed the error message:
enter image description here

Does anyone know which part I missed here? Is it possible to pass a defined function as a parameter to osascript? If anyone can give me a hand, that would be great!

1 Answer 1

0

hello is a function defined within a shell script, it can only be called by bash code from within the script itself. It is not accessible directly from the command line (your screen shot) nor from within Applescript (your osascript call).

To resolve this, you need to turn your hello function into a shell script itself.

3
  • Thank for the explanation! It makes sense. Could you point me to how to turn the hello function into a shell script? I just tried to convert it to a script with export -f hello in /usr/local/bin and then ran my original script again, but it still showed the same error. I have checked which hello but it didn't show anything. Does that mean the exporting was incorrect and not working?
    – Andy Lu
    Feb 18 at 11:51
  • 1
    It's working now. I copied and pasted echo "Hello World" into a new script file, put it under /usr/local/bin, ran source ~/.bash_prrofile in the terminal, set the permission for the script and ran hello. Thanks you @nohillside
    – Andy Lu
    Feb 18 at 13:09
  • @AndyLu export is used to make variables defined in script A visible in scripts/binaries called from A.
    – nohillside
    Feb 18 at 15:46

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .