How do I run commands as a non-root user in a script started with root permissions?

If you start your script with root permissions but need to run certain commands as a specific non-root user you can use sudo with the -u option to either run a single command with e.g.

sudo -u USERNAME whoami # outputs USERNAME's user name

or start a subshell and run your commands in it, e.g.:

sudo -u USERNAME bash -c 'whoami;echo $USER' # outputs USERNAME's user name twice

The line in your script doesn't fail actually, you just run only bash as user meteor, and as bash has nothing to do it just exits and the original root shell runs the rest of the script. What you actually want to do (I suppose) is:

…
echo "Trying sudo -u meteor bash"
sudo -u meteor bash -c '\
  echo "$ whoami" && whoami && echo "^^^^^^ meteor expected"
  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh |\
  bash
'
echo "ls -al /home/meteor/.nvm # should be populated"
…

Another way to achieve the same is a here document:

…
echo "Trying sudo -u meteor bash"
sudo -u meteor bash <<EOF
  echo "$ whoami" && whoami && echo "^^^^^^ meteor expected"
  curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.6/install.sh |\
  bash
EOF
echo "ls -al /home/meteor/.nvm # should be populated"
…

If you're in a container environment, the gosu project could be of interest. It is intended to solve the issue that su and sudo have very strange and often annoying TTY and signal-forwarding behavior.

A few nice alternatives are mentioned in the gosu project's README.md:

  1. chroot --userspec may already be installed
  2. su-exec https://github.com/ncopa/su-exec
  3. setpriv from the (Debian) util-linux package https://manpages.debian.org/buster/util-linux/setpriv.1.en.html