]> CyberLeo.Net >> Repos - CDN/shlib.git/blob - lib/sh/suexec.sh
sh/stopwatch: Add 'time' verb to stopwatch, to retrieve just the times
[CDN/shlib.git] / lib / sh / suexec.sh
1 # suexec library script
2 : <<"END_OF_COPYRIGHT"
3
4 Copyright (c) 2000-2012, CyberLeo
5 All rights reserved.
6
7 Redistribution and use in source and binary forms, with or without
8 modification, are permitted provided that the following conditions are met:
9
10     * Redistributions of the source code must retain the above copyright
11       notice, this list of conditions, and the following disclaimer.
12     * Redistributions in binary form must reproduce the above copyright
13       notice, this list of conditions, and the following disclaimer in the
14       documentation and/or other materials provided with the distribution.
15     * Neither the name of the organization nor the names of its contributors
16       may be used to endorse or promote products derived from this software
17       without specific prior written permission.
18
19 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
23 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
25 GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 HOWEVER CAUSED AND ON ANY THEORY OF LIABILTY, WHETHER IN CONTRACT, STRICT
27 LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
28 OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29
30 END_OF_COPYRIGHT
31
32 if [ -z "${__suexec_sh_loaded}" ]
33 then
34   __suexec_sh_loaded=yes
35   
36   # exec a command via sudo/su
37   # Can be used to reexec this process under su/sudo, if run like this from
38   # the top-level:
39   #
40   #  suexec "${0}" "${@}"
41   #
42   # Specify target user name with -u as the first parameter
43   #
44   #  suexec -u user "${0}" "${@}"
45   #
46   # Just as exec, this will replace the current process entirely, and will not
47   # return except upon error.
48   suexec() {
49     user="root"
50     # Set name if user provided
51     if [ "${1}" = "-u" ]
52     then
53       user="${2}"
54       shift 2
55     fi
56     
57     # suexec if needed
58     if [ "$(id -un)" != "${user}" ]
59     then
60       # Find a su/sudo
61       cmd="sudo -u ${user}"
62       [ -x "$(which sudo 2>/dev/null)" ] || cmd="su ${user} -c"
63       exec ${cmd} "${@}"
64     fi
65   }
66 fi