Concatenating commands using AS variables in do shell script fails

Hi,
I can’t get syntax right to concatenate some do shell script commands when using AS variables.
The first three examples work but, the fourth fails. Why?

-- these are the single commands, they work
do shell script "touch /Users/username/Desktop/test.txt"
do shell script "echo line-1 >> /Users/username/Desktop/test.txt"
do shell script "echo line-2 >> /Users/username/Desktop/test.txt"

-- concatenating like this, works
do shell script "touch /Users/username/Desktop/test.txt;echo line-1 >> /Users/username/Desktop/test.txt;echo line-2 >> /Users/username/Desktop/test.txt"

-- or concatenating using a variable in the touch command, works as well
set myfile to quoted form of POSIX path of (path to desktop as text) & "test.txt"
do shell script "touch & myfile;echo line-1 >> /Users/username/Desktop/test.txt;echo line-2 >> /Users/username/Desktop/test.txt"

Here it is where I need your help, badly.
I tried many way of replacing the full path with the variable in the echo commands as well, but all failed. This is one failure:

-- but this fails -- why? -- how should it be written?
set myfile to quoted form of POSIX path of (path to desktop as text) & "test.txt"
do shell script "touch & myfile;echo line-1 >> & myfile;echo line-2 >> & myfile"
-- Replies --> error "sh: -c: line 0: syntax error near unexpected token `&'
-- sh: -c: line 0: `touch & myfile;echo line-1 >> & myfile;echo line-2 >> & myfile'" number 2

How can I fix it?

Hi,

you mixed up the variable with the literals, try


do shell script "touch " & myfile & " ;echo line-1 >> " & myfile & " ;echo line-2 >> " & myfile

I certainly did. I knew the correct syntax but my brain was probably scrambled, badly :|. Looking at my various tries, I had one really close but no cigar ;).
Many thanks for the fix :cool:.

I’m still a bit puzzled by the touch part, which seems to accept deviations from the correct syntax, such as:
["touch & myfile] instead of the correct ["touch " & myfile & " ]
This shouldn’t work but it does. Why?

-- the "touch" command doesn't seem to follow the rules
set myfile to quoted form of POSIX path of (path to desktop as text) & "test.txt"
do shell script "touch & myfile;echo line-1 >> " & myfile & " ;echo line-2 >> " & myfile

Cheers, Chris

I hope this makes it clear


set myFile to "/Users/me/Desktop/text.txt"

set touch1 to "touch " & myFile --> "touch /Users/me/Desktop/text.txt"
set touch2 to "touch  & myFile" --> "touch  & myFile"

Very. Thanks Stefan.

TIP: When variables are multiple times used I like to put them as a variable in the shell command.


do shell script "myfile=" & quoted form of myfile & linefeed & "touch $myfile ;echo line-1 >> $myfile ;echo line-2 >> $myfile"

p.s. Always use quoted form even if the path doesn’t contain spaces (it can contain other special characters).

myfile is quoted in all relevant posts :wink:

Not in post #4 ;). But I have overlooked the line above :expressionless: