Search code examples
htmlbashmacosshellautomator

Generate an HTML file with variables in shell (Automator)


Basically, I have this "workflow" that I find myself doing frequently and would love to automate:

  1. create a folder with a new name in a specific folder (the path doesn't change)
  2. create an index.html file in that folder
  3. edit the index.html with 2 key variables (A web title and an https: link)
  4. run a script

Here's how far I've gotten in Automator:

  1. Ask for new folder name
  2. Save as variable
  3. Ask for web title name
  4. Save as variable
  5. Ask for link
  6. Save as variable
  7. Run shell script to cd to the right folder and "touch index.html"

Now I'm stuck. How would I edit the index.html while using the two other variables mentioned. Is there a way to edit or "replace" the file's contents while using Automator variable?

TIA!


Solution

  • Try adding the following to 'Run Shell Script' in the Automator workflow:

    for var in $@
    do
      echo $var >> /path/to/index.html
    done
    

    and then setting "Pass input:" above the "Run Shell Script" module to: 'as arguments'

    What this loop does is run the commands between do and done for every single variable you set in your Automator script. Alternatively, you can just replace for var in $@ to for var, as an empty for will automatically collect the variables.

    > and >> are bash shell operators. >> appends to a file or creates the file if it doesn't exist. The > overwrites the file if it exists or creates it if it doesn't exist. You may remove the touch command, unless you wish to create an empty file no matter if any variables are supplied.

    If you need to differentiate between your variables, you don't even need a for loop, and can simply run:

    echo $1 >> /path/to/index.html
    echo $2 >> "/path to/index.html" # *or* /path\ to/index.html 
      # ^ if the directory of the file contains spaces
    echo "The third supplied variable is: ${3}" >> /path/to/index.html
      # ^ if you wish to add additional text to the variable
    

    and so on, following the order in which you set your automator variables. Just make sure "Pass input:" is still set to 'as arguments'.