1

How can I write a gem install or apt-get install in bash without letting it use 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
5
  • 1
    do you want to prevent a script from being executed as sudo ? or what !
    – Yunus
    Feb 1 '16 at 8:36
  • an single command in it .... prevent gem install to run as sudo
    – HlT
    Feb 1 '16 at 8:38
  • it is not working.. i did something wrong..
    – HlT
    Feb 1 '16 at 9:47
  • 1
    I don't understand. If you wan a command to not be run with sudo then don't add sudo in front of that command. Please edit your question and clarify what you are trying to do and how it is failing.
    – terdon
    Feb 1 '16 at 9:52
  • It could be that you want to update your sudoers file to use NOPASSWD: option for use with this specific script.
    – Otheus
    Feb 1 '16 at 17:20
2
#!/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

since you are an admin (normal user) the variable $EUID always greater than zero !
and in root $EUID = 0

((expression)) The expression is evaluated according to the rules described below under ARITHMETIC EVALUATION. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. This is exactly equivalent to let "expression"

or

#!/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

i prefer this one

((EUID)) || exit 1

or

((!EUID)) && exit 1

enter image description here

updates after question edit

#!/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

now it will run in both root and non-root users but it will exec only a part of the script according to the EUID

2
  • I m getting an error like 'The SSH command responded with a non-zero exit status. Vagrant assumes that this means the command failed. The output for this command should be in the log above. Please read the output to determine what went wrong.'
    – HlT
    Feb 1 '16 at 9:22
  • Won't this solution fail for a logged in root user too?
    – roaima
    Feb 1 '16 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.