How Can I Use [ifconfig | grep "inet " | grep -v 127.0.0.1] in Terminal using AppleScript

981 Views Asked by At

I'm new to AppleScript. I am trying small projects and improve on my knowledge for bigger projects.

My attempt is to extract specific network info using ifconfig. I've tried this, but returns

"Expected end of line but found identifier."

Then "inet" is highlighted. Removing "" from inet shows more lines than I want. What's the syntax for multiple commands within a command?

tell application "Terminal" to activate
delay 2
tell application "System Events" to tell "Terminal"
    keystroke "ifconfig | grep "inet " | grep -v 127.0.0.1"
end tell
2

There are 2 best solutions below

0
user3439894 On

The following example AppleScript code will do what you are trying to do:

Example AppleScript code:

tell application "Terminal"
    activate
    do script "ifconfig | grep 'inet ' | grep -v '127.0.0.1'"
end tell
2
Gordon Davisson On

The immediate problem is that quotes don't nest. When you use this:

"ifconfig | grep "inet " | grep -v 127.0.0.1"

...that's two double-quoted strings, "ifconfig | grep " and " | grep -v 127.0.0.1", with some weird inet thing between them. To include double-quotes in a double-quoted string, you need to escape them:

"ifconfig | grep \"inet \" | grep -v 127.0.0.1"

The second problem is that Terminal doesn't accept keystrokes directly, so you'd need to leave off the ...to tell "Terminal" part. But I'd recommend using do shell script instead of trying to control the Terminal application:

set IPinfo to (do shell script "ifconfig | grep \"inet \" | grep -v 127.0.0.1")

(The parentheses are not needed here, but I prefer to include them for readability.)