I'm setting up a server config with cloud init and am running commands one after another in the config file.
One of the commands I need to run to setup my server's environment is PM2 to keep a node server app online after reboot. I am able to have PM2 output a special command I need to run and am storing that command in a variable to run in the next line.
Command 1: (Storing the Output)
pm2response=$(pm2 startup systemd)Command 2: (Executing the response command and trimming extra logging)
${pm2response#*Execute the following command:}When I run Command 2 in my playground server, it outputs the error
[PM2][ERROR] Init system not foundI don't understand why I can't store the command output in a variable and execute the variable. I have manually copied the exact command I need to run into the console and successfully executed it. It's just storing it in a variable that doesn't work.
Command I need to execute as a variable: (This works successfully)
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/usernameCommand I tried executing as a variable: (Has errors)
var='sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username'
$varWhy won't this work?
Update
I got the $var to work using double quotes in my server.
var="sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username"
$var #works!Although this is just an example I was testing in a playground server. For clarity of the question, I'm really trying to evaluate Command 2:
${pm2response#*Execute the following command:}Reference for Command 2: I'm using the shell parameter substitution so I can remove logging. This is the output without the shell parameter substitution.
echo $pm2response: (will output)
[PM2] Init System found: systemd [PM2] You have to run this command as root. Execute the following command: sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/usernameSo by adding shell parameter substitution,echo ${pm2response#*Execute the following command:}: (will output)
sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username 3 1 Answer
Try either of these lines:
var="sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username"
$var
var1=$("sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username")
$var1The error on the one you used happens because expressions don't expand in single quotes, use double quotes for that:
var='sudo env PATH=$PATH:/usr/bin /usr/lib/node_modules/pm2/bin/pm2 startup systemd -u username --hp /home/username'
$var 2