我怎样才能写一个gem install
or apt-get install
inbash
而不让它使用sudo
?
#!/usr/bin/env bash
apt-get update -y
apt-get upgrade -y
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
\curl -sSL https://get.rvm.io | bash -s stable --ruby
source /usr/local/rvm/scripts/rvm
((EUID)) || exit
gem install jekyll
答案1
#!/usr/bin/env bash
((!EUID)) && { # check if the EUID is a zero
echo "${0##*/} can not be executed as root " # notify
exit 1 # exist with status code 1
}
gem install jekyll
由于您是管理员(普通用户),变量 $EUID 始终大于零!
并在根 $EUID = 0
((表达式)) 表达式根据下面算术评估中描述的规则进行评估。如果表达式的值非零,则返回状态为0;否则返回状态为1。这与let“表达式”完全相同
或者
#!/usr/bin/env bash
[[ $EUID = 0 ]] && { # check if the EUID is eq to zero
echo "${0##*/} can not be executed as root " # notify
exit 1 # exist with status code 1
}
gem install jekyll
我更喜欢这个
((EUID)) || exit 1
或者
((!EUID)) && exit 1
问题编辑后更新
#!/usr/bin/env bash
((!EUID)) && {
#stuff to be exec as root
for option in update 'upgrade -y'
do
apt-get $option
done
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
\curl -sSL https://get.rvm.io | bash -s stable --ruby
source /usr/local/rvm/scripts/rvm
} || {
#stuff to be exec as non-root
gem install jekyll
}
exit 0
现在它可以在 root 和非 root 用户中运行,但它只会根据 EUID 执行脚本的一部分