2

How do I grab input from the user in AppleScript and then pass the result of the variable to a do shell script command from within AppleScript itself?

For example, the user would type the answer foo to the following dialog box:

display dialog "Please enter your username" default answer ""
set the userID to the text returned of the result
do shell script "rm -rf /Users/$userID/.Trash/*" with administrator privileges

So in this instance, if I were to incorporate the answer of foo in lieu of $userID, it would read as the following when it executes the command:

display dialog "Please enter your username" default answer ""
set the userID to the text returned of the result
do shell script "rm -rf /Users/foo/.Trash/*" with administrator privileges

How do I pass that variable I grabbed earlier, in this case it would be $userID and incorporate it into the middle of the shell script call that I have made just above.

2

This assigns the name entered to the variable answer.

display dialog "What's your name?" default answer ""
set answer to text returned of result
display dialog "Your name is " & answer
  • I know how to do that. I'll re-word my question to provide more clarity. – Danijel-James W Oct 28 '13 at 5:07
  • I don't want to add answer to a dialog as text, I want to pass, pipe, parse - whichever - it into the middle of a do shell script command – Danijel-James W Oct 28 '13 at 5:14
  • Instead of display dialog you put the command you need. The user input is stored in a variable. It seems you are actually asking how to concatenate strings. This is done with the & operator as shown in the last line of the example. – khowl Oct 28 '13 at 7:56
  • I used your script answer to answer my own question using it to do this. Thank you. display dialog "Your name is " & answer & ", how are you?" – Danijel-James W Oct 28 '13 at 9:37
1

You need string concatenation (the & operator) to combine the “fixed” parts of you string with the variable part. You also should use the quoted form of command to make sure that all user inputs are handled safely (i.e. spaces, wildcards, quote characters, and other characters that the shell treats specially—none of these are likely in a “short user name” but it always a good idea to handled things safely):

display dialog "Please enter your username" default answer ""
set the userID to the text returned of the result
do shell script "rm -rf /Users/"& quoted form of userID & "/.Trash/*" with administrator privileges

You can also pass the rest of the pathname through quoted form of, but you must not include the wildcard:

… "rm -rf " & quoted form of ("/Users/"& userID & "/.Trash/") & "*" …

You must log in to answer this question.

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