首页 / 操作系统 / Linux / Bash强制脚本使用某用户执行
受oneStack脚本启发:
原来是可以轻松实现强制脚本使用某用户权限执行的。脚本内容如下:#!/bin/bash
# filename: test.sh
# email: linux@linuxidc.com
# date: 2013-09-02
user="root"
if [ `whoami` != "${user}" ]; then
exec su - "${user}" -c "sh ${PWD}/test.sh"
fi
echo "以下为脚本主体内容"
id
echo "执行id命令结束"调试信息如下:linuxied.com @localhost:~$ sh -x test.sh
+ user=root
+ whoami
+ [ xiaoyuwang != root ]
+ exec su - root -c sh /home/xiaoyuwang/test.sh
Password:
以下为脚本主体内容
uid=0(root) gid=0(root) groups=0(root)
执行id命令结束推荐阅读:Linux Bash Shell入门教程 http://www.linuxidc.com/Linux/2013-08/88487.htmBash脚本之for语句if语句以及各种测试语句 http://www.linuxidc.com/Linux/2013-07/87922.htm在 Bash shell 中读取用户输入 http://www.linuxidc.com/Linux/2013-03/81185.htmBash Shell 入门指导手册 http://www.linuxidc.com/Linux/2012-10/72264.htm什么是Bash Shell的内建(build in)命令 http://www.linuxidc.com/Linux/2013-06/86039.htm