BIG filesize causes error in 'do shell script' when writing a tempfile

I am using text files stored in the TemporaryItems folder to peek at results when they are too large for viewing in a “display dialog” or a “choose from list” pop-up.

It has worked quite nicely to open a temp file in a predefined app and window, then simply use display dialogs to manipulate the temp file. An example of a lengthy result would be viewing a log, or a search via mdfind resulting in dozens of lengthy path-strings which are illegibly wrapped in a vanilla applescript display.

One such search resulted in a text file of over 1 million characters which gave me an error. (I know… search smaller by using ‘-onlyin’ !)
Incremental tests seem to reveal a size limit that I could not explain.
I can certainly work around the issue with a try handler, but I’d like to know if there is a better way to handle larger files.

I’ve stripped away the rest of the code to narrow down this example of the problem. Any thought about why this happens would be appreciated!

•set toomany to 1 to reproduce the error
or
•set toomany to 0 to avoid the error


##generate text string
set toomany to 1 --[ use 0 to avoid fails, or 1 to trigger err! ]
set txt to ""
repeat ((100000 * 0.52309499) + toomany) times --[ 0.52309499=OK, but...  0.52309500 fails!!! ]
	set txt to txt & " blah"--[file contents will be ''blah blah blah...etc.'']
end repeat

##generate a temp file
set nam to (every word of (do shell script "date")) as text --[filename is just a timestring]
set pth to POSIX path of (path to temporary items from user domain) & nam
do shell script "echo " & quoted form of txt & " > " & quoted form of pth -------->error "The command exited with a non-zero status." number 255

##verify temp file and open it 
set psxFYL to (POSIX file pth)
tell application "Finder"
	open (path to temporary items from user domain)
	if exists psxFYL then
		select psxFYL
		open psxFYL
	end if
end tell

Model: Mac Pro, Yosemite
AppleScript: 2.7
Browser: Safari 601.2.7
Operating System: macOS 10.14

It’s explained here:

https://developer.apple.com/library/archive/technotes/tn2065/_index.html#//apple_ref/doc/uid/DTS10003093-CH1-TNTAG6-HOW_LONG_CAN_MY_COMMAND_BE__REALLY_

Easy: stop using do shell script to write the files. Use AppleScript’s write command instead:

set theFile to ((path to temporary items from user domain as text) & nam) as «class furl»
set fileRef to open for access theFile with write permission
set eof fileRef to 0
write txt to fileRef as «class utf8»
close access fileRef

Thanks Shane, that worked perfectly. And the link was very informative!