如果我在脚本中更改用户,为什么运行 su 的脚本似乎永远不会终止?

Čam*_*amo 11 bash scripts composer

我有一个非常简单的 bash 脚本,其中有 5 个在 root 用户下运行的命令。如果我一一手动运行命令,一切正常 - 没问题。但是当我通过命令将它作为 my-deploy.sh 文件运行时

bash /root/custom-scripts/deploy/my-deploy.sh 2>> /var/log/www-deploy/tatrytec.eu.log
Run Code Online (Sandbox Code Playgroud)

这似乎是一个永无止境的过程。这是脚本:

#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

cd /var/www/html/tatrytec.eu

git pull

# Change user bacause of composer install warrning
su vlado

composer install  --no-scripts

npm install --production
Run Code Online (Sandbox Code Playgroud)

它开始运行,我可以在终端中看到 git pull 的结果。但是然后它就死了,没有任何错误,它仍在运行。我可以通过 ctrl+Y 停止它。我觉得那个用户有问题,但正如我之前写的那样,如果我一个一个运行命令,它就可以工作。我不明白。有人可以告诉我可能是什么问题吗?谢谢。

Arc*_*mar 13

  1. su vlado除非以 root 身份运行,否则将需要密码
  2. su vlado 将等待输入
  3. 之后su valdo的命令不在内部执行su,而是在退出后执行su valdo

发生什么事

cd /var/www/html/tatrytec.eu  # change dir

git pull # pull git repos

# Change user bacause of composer install warrning
su vlado # either ask password or wait for input

composer install  --no-scripts # if this get executed, you are no longer as vlado
Run Code Online (Sandbox Code Playgroud)
  • 关键是这su vlado将派生一个新的 shell,它将忽略(原样)原始 bash 脚本中的以下行。
  • 复制/粘贴时没有这个限制(当你在 vlado 的新 shell 中复制时)

我尝试更详细地解释哪个用户/发生了什么

cd /var/www/html/tatrytec.eu  # ROOT change dir

git pull # ROOT pull git repos

# Change user bacause of composer install warrning
su vlado # VLADO wait for input
new shells as VLADO> sample command
new shells as VALDO> exit

composer install  --no-scripts # ROOT run composer
Run Code Online (Sandbox Code Playgroud)

建议更正

作为根

#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

cd /var/www/html/tatrytec.eu

git pull

# Change user bacause of composer install warrning
su vlado  <<EOF

composer install  --no-scripts

npm install --production

EOF
Run Code Online (Sandbox Code Playgroud)

在哪里

  • su vlado << EOF...EOF将所有行输入到su vlado


mch*_*hid 10

改用这个:

#!/bin/bash
# Run this script as bash command like: bash create-apache-site.sh

cd /var/www/html/tatrytec.eu

git pull

# Change user bacause of composer install warrning
su vlado -c 'composer install  --no-scripts; npm install --production'
Run Code Online (Sandbox Code Playgroud)

-c--command为选项su允许你运行一个命令。


Ous*_*ama 1

您似乎想以用户 vlado 的身份运行脚本中的最后几行。有一个干净的方法可以做到这一点:

sudo -u vlado  your_command 
Run Code Online (Sandbox Code Playgroud)

所以脚本的最后几行将如下所示:

sudo -u vlado composer install --no-scripts
sudo -u vlado npm install --production
Run Code Online (Sandbox Code Playgroud)