Home > Software engineering >  Defined bash commands not found when passed in "do shell script" in osascript
Defined bash commands not found when passed in "do shell script" in osascript

Time:02-19

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 was 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!

CodePudding user response:

Your script will work fine if the function hello() is defined inside the .bashrc or .bash_profile or .zshrc (depends on which shell you are using).

The issue here is, when you are calling osascript to create a new terminal, the newly created terminal doesn't know about a function (or command) named hello.

So, you have to define it in such a way that every newly created terminal knows about that command. So, either you could put it in your .bashrc or you can create a shell script named hello in your $PATH and put the required code in that script.

  • Related