bash脚本中使用su切换用户执行命令失败及返回root的疑问
bash脚本中使用su切换用户执行命令失败及返回root的疑问
我来给你梳理一下问题出在哪哈~
首先说为什么脚本里的cd live会报错:当你在脚本里执行sudo su - mastodon的时候,这个命令会启动一个全新的交互式shell,此时脚本的执行流程会暂停,直到你手动退出这个mastodon的shell才会继续。也就是说,你看到终端切换到mastodon用户后,后面的cd live、那些Rails命令其实根本没在mastodon的shell里跑,而是等你退出mastodon shell后,回到root的shell才执行,这时候root当前目录里没有live文件夹,自然就报错了。
再来说你的第二个疑问:原来脚本里的exit其实根本不会被执行,因为sudo su - mastodon启动的交互shell会卡住脚本流程,直到你手动输入exit退出,后面的systemctl restart命令也根本没机会运行。
下面给你两种可行的解决方案,让命令能正确在mastodon用户下执行,之后自动回到root环境运行重启命令:
方案一:使用su -c参数批量执行命令
通过-c参数把要在mastodon用户下执行的命令打包成一个字符串,让su切换用户后直接执行这些命令,而非启动交互shell:
#!/bin/bash # 切换到mastodon用户并执行指定命令组 sudo su - mastodon -c " cd live RAILS_ENV=production bundle exec rake tmp:cache:clear RAILS_ENV=production bundle exec rails assets:generate_static_pages RAILS_ENV=production bundle exec rails assets:precompile " # 自动回到root环境,执行重启操作 systemctl restart mastodon-*
方案二:使用Here-doc批量执行命令
这种方式可读性更好,适合命令较多的场景,通过输入流把命令传给su启动的shell:
#!/bin/bash sudo su - mastodon << EOF cd live RAILS_ENV=production bundle exec rake tmp:cache:clear RAILS_ENV=production bundle exec rails assets:generate_static_pages RAILS_ENV=production bundle exec rails assets:precompile EOF # 命令执行完自动回到root环境,执行重启 systemctl restart mastodon-*
这两种方式都不需要手动输入exit,命令执行完毕后会自动回到root的shell,继续运行后面的重启命令。
备注:内容来源于stack exchange,提问作者BlueDogRanch




