Applescript loop through result of "ls" with "do shell script" - macos

I have selected a list of files in Applescript using:
set variableName to do shell script "cd /; cd dev/; ls tty.usb*"
When I print out variableName, it shows this list:
file1
file2
From here, I want to loop through each of them using:
repeat with theItem in variableName
display dialog theItem
end repeat
Instead of showing "file1" and "file2" one by one, it shows "f, i, l, e, 1," and so forth.
How can I loop the list to get a complete file name?

Thanks for the helpful responses! I have found out the solution.
set variableName to do shell script "find /dev/tty.usb*"
display dialog variableName
set testArray to paragraphs of the variableName
repeat with theItem in testArray
display dialog theItem
end repeat
By using paragraphs, I'm able to split by newline and covert the result into a list.

Related

How to pass several variables from Shell Script to AppleScript in Automator?

There is an excellent answer for the reverse, pass several variables from AppleScript to Shell Script but I can't find a comprehensive answer for the opposite when there are two or more variables/arguments and or a bash function.
In Automator I am trying to pass variables like so: Run AppleScript > Run Shell Script > Run AppleScript.
Run AppleScript: which passes a URL as an argument
Run Shell Script: which uses "$#" for that argument
/bin/bash serial=$(($RANDOM % 10000)) /usr/local/bin/ffmpeg -i "$#" -c copy bsf:a aac_adtstoasc "/Path/to/file/movie_$serial.mp4" 2>&1 $! exit 0
Run AppleScript: This is where I need to pick up stdout, and the PID of the last executed process ffmpeg from Run Shell Script above. I can't seem to get anything. I have tried adding an automator "Storage Variable" but it's not receiving.
Using AppleScript's Do Shell Script command I couldn't get serial=$(($RANDOM % 10000)) to actually put a serial number in the file name movie_$serial.mp4. The file name was literally output as "movie_$serial.mp4", instead of "movie_1234.mp4".
serial=$(($RANDOM % 10000)) works perfectly in Terminal and in Run Shell Script. Not sure what I am missing to make it work with "Do Shell Script".
do shell script "/bin/bash serial=$(($RANDOM % 10000)); /usr/local/bin/ffmpeg -i " & link_ & ffmpegOpt & "'" & sPath & "$serial.mp4" & "'"
Which returns the following for the "do shell script" call:
"/bin/bash serial=$(($RANDOM % 10000)); /usr/local/bin/ffmpeg -i urlofmovie -c copy -bsf:a aac_adtstoasc '/Path/to/file/movie_$serial.mp4'"
When using ffmpeg the path on the command line the save path has to be in quotes.
If I read your OP correctly, you actually have two different issue here.
Not knowing how to provide input to a Run AppleScript action from a Run Shell Script action.
Variable parameter expansion is not occurring for you with: $serial
Issue 1:
To return something from a Run Shell Script action to another action. e.g. a Run AppleScript action, set the last line of the Run Shell Script action to, e.g.:
echo "foobar"
Or:
printf "foobar"
For multiple items use, e.g.:
echo "foobar
barfoo"
Or:
printf "foobar\nbarfoo"
Issue 2:
I am not in the position to replicate your do shell script command at the moment; however, the reason variable parameter expansion is not occurring is because the variable has single-quotes around it.
... '/Path/to/file/movie_$serial.mp4'"
Expansion will not take place when a variable has single-quotes around it, so you need to formulate your command so it can be expanded. Or in a separate step, process what's necessary to to accomplish the goal.
For example:
set sPath to "/path/to/file/movie_"
set serial to ((random number from 0 to 32727) mod 10000) as string
set pathFilename to sPath & serial & ".mp4"
Then you can use, e.g.:
... & pathFilename's quoted form
In your do shell script command while adjusting the entire command to work for you.
In other words, you can get rid of, e.g.:
/bin/bash serial=$(($RANDOM % 10000));
And:
& "'" & sPath & "$serial.mp4" & "'"
When running a shell script from Script Editor and wanting to return more than one argument as input; and assign those arguments to variables in your Apple Script:
One method I discovered:
Example shell script:
SHELL_VAR1=$(date)
SHELL_VAR2=$(whoami)
echo "$SHELL_VAR1","$SHELL_VAR2"
The echo command at the end, with a comma for delimiter, will output to Apple Script in this format:
{"January 21, 2022", "john"}
In the Apple Script:
set input to (do shell script "script.sh")
set the text item delimiters to ","
set {var1, var2} to {text item 1, text item 2} of the input
{var1, var2}
If there is another, simpler, method I would love to learn it.
Is there a special notation for multiple arguments that Apple Script can use for input?
i.e. $1 $2 or something similar

Automator - dealing with spaces on paths that will be passed from Applescript to Shell Script

I have an AppleScript processing paths in the alias form and converting them to posix.
These paths will be processed by a shell script in the second step of this automator workflow.
The problem is that the path contains spaces.
I don't know how to deal with this, so I have this subroutine to remove any space and replace it with \.
on replaceChars(this_text, search_string, replacement_string)
set saveTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to the search_string
set the item_list to every text item of this_text
set AppleScript's text item delimiters to the replacement_string
set this_text to the item_list as string
set AppleScript's text item delimiters to saveTID
return this_text
end replaceChars
On the Applescript part I do
-- convert the path from the alias form to posix
set fileInputPosix to (the POSIX path of thePath)
-- replace " " with "\ "
set quotedForm to replaceChars(fileInputPosix, space, "\\ ")
at this point the paths appear to be ok, something like
'/Users/myUser/Desktop/my\ video\ file.png'
but when I pass this path to the shell script it will not accept that.
In a very similar situation to your other question, you seem to be creating a problem that doesn't need solving by choosing to use an AppleScript action to receive file paths that ultimately end up being passed into a shell script action. It appears the only reason for doing this is to have the AppleScript "process" the file paths as alias file references, converting them into posix paths for the purpose of using them as command-line arguments in a shell script.
This is not at all necessary. Even if you decide an AppleScript is necessary for other reasons, Automator will often convert incompatible data types to an appropriate format when passing them between actions†, so an AppleScript alias reference can be happily sent onto a shell script action, which will automagically receive them as posix file paths:
In the above screenshot, you can see that no processing or manipulation was performed by me at any stage, and both scripting actions return the correct file path one would expect for the language.
Conclusion
▸ Remove your AppleScript actions, and simply send the files directly through to the shell script, as arguments, and enclose your command-line argument variables in quotes as #vadian has already demonstrated.
▸ If you use an AppleScript for other reasons, that's fine. Just leave the alias references exactly as they are, and send them on afterwards to the shell script, and treat them the same way as just described.
†File paths sent in the other direction—from a shell script to an AppleScript—won't, however, magically become alias references. A posix path is little more than a piece of text, and since AppleScript handles text perfectly well, there's no expectation on it to try to coerce it into something different; this would need to be done explicitly by the scripter, if necessary.
Just quote the paths in the shell line and delete the search and replace part
/usr/local/bin/ffmpeg -I "$1" -vf "select=eq(n\,$3)" -vframes 1 "$2"
You can quote the whole string or use quoted form of to intelligently quote the string, and you can also escape individual characters as you are trying to do, but in that case you will need to escape each escape character, for example:
quoted form of “/Users/myUser/Desktop/my video file.png”
“/Users/myUser/Desktop/my\\ video\\ file.png”

How can I echo a value/variable in Applescript?

Disclaimer: I'm very new to this.
I have a number which I retrieved using the count command and now I want to output it to a .txt file using "do shell script echo."
My code so far:
tell application "Things3"
set todayToDos to to dos of list "Today"
count todayToDos
do shell script "echo todayToDos > /Users/nonefirstnonelast/Desktop/Things.txt"
end tell
Console output is:
""
without do shell script "echo todayToDos > /Users/nonefirstnonelast/Desktop/Things.txt" line it is: 27
You have to assign the result of the count line to a variable. Then you have to coerce the integer to text and insert the value of the variable in the shell script line.
tell application "Things3"
set todayToDos to to dos of list "Today"
set numberOfTodos to count todayToDos
end tell
do shell script "echo " & (numberOfTodos as text) & " > /Users/nonefirstnonelast/Desktop/Things.txt"

Applescript to get a list of file's hashes in a folder

I'm working on a script that will grab all files in a folder and compute their hash, however I'm having trouble on what should be one of the most basic parts of the script - concatenating found files into a shell script that will find the hash. Specifically, my problem is with this line:
do shell script "/usr/bin/openssl sha1 " & quoted form of POSIX path of new_file
It's line 44 of the script as a whole, here: http://pastebin.com/fEuFg9xL
My error is "Can't make quoted form of POSIX path of item 1 of {the list of files} into type unicode text".
Thanks in advance!
new_file is just a item of a list. You need it as text (like you already did couple of times in your code).
do shell script "openssl sha1 " & quoted form of POSIX path of (new_file as text)

How to pass a variable FROM applescript TO a shell script?

I have the following script
#!/bin/bash
/usr/bin/osascript << EOT
set myfile to choose file
EOT
no_ext=$(python -c "print '$myfile'.split('.')[0]")
### this works - just need to know how to pass the arg
R CMD Sweave no_ext.Rnw
pdflatex no_ext.tex
open no_ext.pdf
Can anyone point me to "how to pass the variable myfile correctly" ?
EDIT
Thx for all the suggestions!
Don't know what to accept, all of your answers really helped me since I learned a lot from everybody.
The following problems exist in your script:
A variable set in the AppleScript section does become defined in the enclosing shell script. You have to do the data exchange with the shell script by using command substitution.
AppleScripts invoked from a shell script aren't allowed to do user interaction because they do not have an application context. You can use the helper application "AppleScript Runner" to run user interaction commands.
Here is a revised version of your script where those problems are fixed:
#!/bin/bash
myfile=$(/usr/bin/osascript << EOT
tell app "AppleScript Runner"
activate
return posix path of (choose file)
end
EOT)
if [ $? -eq 0 ]
then
echo $myfile
else
echo "User canceled"
fi
First, you need to get the contents of the myfile variable from Applescript to bash. I don't know Applescript, so I'll make a shot in the dark as to how to write to its standard output. Then the python part is just unnecessary complexity (and likely wrong anyway, you were throwing away everything after the first . rather than the last). Next you need a $ before the variable name in bash syntax. I think the following script does what you want:
#!/bin/sh
set -e
myfile=$(osascript <<EOT
set myfile to choose file
write myfile to stdout
EOT
)
no_ext="${myfile%.*}"
R CMD Sweave "$no_ext.Rnw"
pdflatex "$no_ext.tex"
open "$no_ext.pdf"
(set -e at the beginning makes the shell exit immediately if an error occurs, instead of trying to execute pdflatex even though no .tex file has been produced or somesuch.)
Realize that applescript paths are colon ":" delimited. You need slash delimited in bash so in applescript terms that's the "posix path". Also, when using osascript it can't open dialog windows. You must tell an application to open the window. Next, you "return" something from the applescript... that's what goes to bash. Finally, in bash to execute a command and assign the result to a variable use `` around the command. So knowing this here's a shell script to use an applescript to get the myFile variable.
#!/bin/bash
myFile=`/usr/bin/osascript << EOT
tell application "Finder"
activate
set myfile to choose file with prompt "Select the file to use in bash!"
end tell
return (posix path of myfile)
EOT`
echo $myFile

Resources