User input assigned to variable in AppleScript then passed to "do shell script" command

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.


Solution 1:

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

Solution 2:

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/") & "*" …