Do not forget semicolons when running sh c

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the bash category.

Last Updated: 2024-04-25

I had the following code:

/bin/sh -c '
  echo "README: THIS TAKES UP TO HALF A MINUTE TO BOOT"
  sleep 20
  wp core install --path=/usr/src/html --url="http://localhost:${WEB_PORT-80}" \
    --title="${TITLE-Wordpress Local}" --admin_user="${ADMIN_USER-admin}" \
    --admin_password="${ADMIN_PASSWORD-mypassword}" --admin_email="${ADMIN_EMAIL-admin@example.com}"
'

It didn't work. And, weirdly, it just printed out the commands instead of executing them. Here's the output I got:

"README: THIS TAKES UP TO HALF A MINUTE TO BOOT" sleep 20 wp core install --path=/usr/src/html --url="http://localhost:${WEB_PORT-80}" \
  --title="${TITLE-Project P Local}" --admin_user="${ADMIN_USER-admin}" \
  --admin_password="${ADMIN_PASSWORD-mypassword}" --admin_email="${ADMIN_EMAIL-admin@example.com}"

So here's the issue: a newline was insufficient to communicate "next command". I needed to have a semicolon after each one, otherwise the sh -c command would not know where one command stopped and the next one began. Here's the fix:

/bin/sh -c '
  echo "README: THIS TAKES UP TO HALF A MINUTE TO BOOT";
  sleep 20;
  wp core install --path=/usr/src/html --url="http://localhost:${WEB_PORT-80}" \
    --title="${TITLE-Project P Local}" --admin_user="${ADMIN_USER-admin}" \
    --admin_password="${ADMIN_PASSWORD-mypassword}" --admin_email="${ADMIN_EMAIL-admin@example.com}";
'

Lesson:

Unlike in regular bash scripts, you need semicolons between commands that are run in a string with sh -c