如何在脚本中启动MongoDB?解决‘mongod: unrecognized service’报错
Hey there! I’ve run into this exact frustrating issue before—commands working flawlessly in the terminal but failing when run in a script. Let’s break down the most likely causes and how to fix them:
Use absolute paths for the
servicecommand
Your terminal’sPATHenvironment variable might include directories that your script’s non-interactive environment doesn’t. First, find where theservicecommand lives by running this in your terminal:which serviceIt’ll probably output something like
/usr/sbin/service. Update your script to use this full path instead of justservice:sudo /usr/sbin/service mongod startLoad your shell’s environment variables in the script
Interactive terminals load files like~/.bashrcor~/.profilethat set up your environment, but scripts run in a non-interactive shell and skip these. Add this line at the top of your script (before the mongod command) to load your user’s environment:source ~/.bashrcIf you’re running the script with
sudoand it’s using root’s environment, try sourcing/root/.bashrcinstead.Switch to
systemctlif your system uses systemd
Many modern Linux distros use systemd instead of the old SysV init system, and theservicecommand is just a compatibility wrapper. Ifsudo systemctl start mongodworks in your terminal, replace theservicecommand in your script with this one—it’s more reliable in script contexts.Fix sudo’s restricted PATH
Sudo often uses a stripped-downPATHby default, which might exclude the directory whereserviceor mongod’s init scripts live. You can either explicitly set the PATH in your command:PATH=/usr/sbin:/usr/bin:/sbin:/bin sudo service mongod startOr edit the
sudoersfile (always usevisudoto do this safely) to keep your user’s PATH when using sudo. Look for a line starting withDefaultsand add:Defaults env_keep += "PATH"Check your script’s shebang line
Make sure the first line of your script is set to use bash instead of the more minimal sh:#!/bin/bashSome systems link
/bin/shto dash, which has a more limited environment that can cause issues with commands that work in bash.
Give these steps a try—one of them should get your script running the mongod service correctly!
内容的提问来源于stack exchange,提问作者Jon




