[solved] sudo command in a Bash function?

Hello there,
I need to use sudo inside of a Bash function in order to allow my laptop to hibernate after a certain time using "systemctl hibernate".
However, I cannot figure out what's the correct way to include sudo inside of my function snippet:
function hibernate {
echo "System is going to hibernate in $1 minute(s)..."
sleep $1m ; systemctl hibernate
alias hibernate_timer=sudo hibernate # sudo misplaced here
Last edited by orschiro (2013-06-26 20:33:47)

you'd need sudo's -E parameter for that, otherwise that function is not defined in the su environment.
EDIT: -E is not sufficient.
man sudoers wrote:In all cases, environment variables with a value beginning with () are
     removed as they could be interpreted as bash functions.  The list of environ‐
     ment variables that sudo allows or denies is contained in the output of “sudo
     -V” when run as root.
You cannot pass functions to sudo - the alias is not relevant, you couldn't do this directly: `sudo hibernate` would fail.
I'd also recommend putting the sudo as "deep" as possible: right on the systemctl command.  There is a reason bash functions are not allowed to be 'sudo'ed - and running sudo on a function that includes a sleep command seem particularly bad to me.
Last edited by Trilby (2013-06-26 17:59:18)

Similar Messages

  • [solved] Trying to make a bash function work for (chroot)

    So this is what I have so far.
    function arch-chroot () {
    sudo & mount /dev/sda1 /mnt
    cd /mnt
    mount -t proc proc proc/
    mount --rbind /sys sys/
    mount --rbind /dev dev/
    mount --rbind /run run/
    chroot /mnt /bin/bash
    I get stuck at cd /mnt. This is how I do it in terminal. I can't quite figure out to move past 'cd'.
    # just use the arch-install-scripts. Simple and easy. ------------
    Last edited by jedijimi (2015-01-25 18:11:19)

    It could be something like this:
    if [[ $EUID != 0 ]]; then
    echo "This script should be ran as root" && exit 1
    fi
    mount -t proc /proc $1/proc
    mount --rbind /sys $1/sys
    mount --rbin /dev $1/dev
    mount --rbind /run $1/run
    chroot $1
    This way it uses the default shell and asks for a new root as a parameter. But instead of reinventing the wheel just install arch-install-scripts as it only weights ~0.05MiB. Also when trilby had asked what do you want to do, he meant why are you using "sudo & ..." as sudo can't be run in background.
    Next time you can't find which package provides certain executable file, just use pkgfile.

  • Sudo Command in Bash Script

    So I created a simple bash script to run on login.....
    one of the commands is the following:
    sudo "something something something"....
    One thing I haven't learned in my years of Unix is how do you get a bash script to run a sudo command without having to enter a password?  I know this is trival, but just a quick 'this is how you do it' would be cool.
    Thanks ahead of time on this really dumb question.

    There's a few ways to do this.  Here's two (pick the method you like):
    Method 1: Using "askpass".
    With this you always do sudo -A command.  The -A argument tells sudo to execute a command that echos the password to stdout.  That command is something you write.  For this explaination let's call the command pw and stick it /usr/local/bin.  So it's full pathname would be /usr/local/bin/pw.
    sudo -A can get the pathname to pw a number of ways.
    1. From the sudoers file.
    Use visudo to add the following line to the sudoers file:
    Defaults:ALL    askpass=/usr/local/bin/pw
    2. Using the SUDO_ASKPASS environment variable.
    export SUDO_ASKPASS=/usr/local/bin/pw
    This might work too (assuming SUDO_ASKPASS has been previously exported):
    SUDO_ASKPASS=/usr/local/bin/pw sudo -A command
    Method 2: Have sudo read the password from stdin
    echo -n password | sudo -S command
    The -S option tells sudo to read the password from stdin so echo pipes it in (without the ending newline).
    The only relatively secure scheme of these two methods is the askpass (-A) method.  At least with that method you have a chance of encrypting/hiding your password down in the command that echoes it to stdout.  The -S method would contain your password explicitly in a script somewhere unless you make other provisions to encrypt/hide it with that technique.

  • I want to disable 'Spotlight' for repairing my disk "Macintosh HD" , but somehow the command 'sudo mdutil -a -i off' does not work in 'Terminal'. I get result as ' bash: sudo: command not found' .I am using OS 10.10.  Please help.

    I want to disable 'Spotlight' for repairing my disk "Macintosh HD" , but somehow the command 'sudo mdutil -a -i off' does not work in 'Terminal'. I get result as ' bash: sudo: command not found' .I am using OS 10.10.  Please help.

    It appears that you may not have a properly installed OS X system.
    You must be connected to the Internet to reinstall OS X.
    In the menu bar, choose Apple menu > Restart. Once your Mac restarts (and the gray screen appears), hold down the Command (⌘) and R keys.
    Select “Disk Utility,” and then click Continue.
    Select your startup disk from the list on the left, and then Repair Disk.
    After disk is repaired, select Reinstall OS X, then click Continue.
    Follow the onscreen instructions. In the pane where you select a disk, select your current OS X disk

  • Can't run bash or sudo commands

    I have a Mac Pro with OS X 10.8.2 and also an older iMac running OS X 10.6.8. On neither Mac can I run any bash or sudo commands! I always get command not found.
    Both Macs have fresh installs of OS X, did I forget to install something? Is X11 needed? or Xcode?
    Thanks for any help.

    Back up all data.
    Select
    Shell ▹ New Command
    from the Terminal menu bar. Copy and paste the following line into the text box that opens:
    mkdir disabled_shell_files; mv .profile .bash* $_
    Your old shell initialization and history files will be saved in a directory with the indicated name at the top level of your home directory.

  • [solved] Need Help with bash function

    I would like to have a bash function that lets me create tar.xz archives. I have the following in my bash now:
    mktar() { tar cf "${1%%/}.tar" "${1%%/}/"; }
    mktgz() { tar czf "${1%%/}.tar.gz" "${1%%/}/"; }
    mktbz() { tar cjf "${1%%/}.tar.bz2" "${1%%/}/"; }
    Any advice would be appreciated.
    Last edited by orphius1970 (2010-09-06 11:10:39)

    orphius1970 should learn some shell scripting.
    $FILE is obviously the archive name and is $1 the first argument.
    $* would be the rest of the arguments (only so after the shift command.
    So, archive archive_name list of files to be archived.
    Example: archive stuff.tar.gz stuff/

  • -bash: sudo: command not found

         Hello all,
    I have had WAY too many problems with this laptop, and at this point in its miserable little life, I've decided to just wipe the hard drive and start fresh, not caring at all what happens to the files left on there. As previously stated in one of my earlier questions (That was, might I add, never fully answered.), this late 2008 MacBook (aluminum) has a problem where it does not boot up, and just endlessly shows the gray spinning pinwheel. Four months later, that just stops, and now when trying to boot up with my normal startup disk, it brings me right to the Recovery disk and tries to reinstall OS X. I tried, it failed 5 minutes in. So I tried to wipe the hard drive, and it says:  Disk Erase failed with the error: Couldn't unmount disk.   I looked it up and I saw that if I went into the Terminal and typed: sudo diskutil unmountDisk /dev/disk0 , it would unmount the disk. But whenever I type that, it says: -bash: sudo: command not found. I have no idea how to fix this, and I would really like to be able to use my laptop again without giving somebody my money to do it for me.
                                                 Thanks,
                                                      Luke

    Clean Install of Snow Leopard
    Be sure to make a backup first because the following procedure will erase
    the drive and everything on it.
         1. Boot the computer using the Snow Leopard Installer Disc or the Disc 1 that came
             with your computer.  Insert the disc into the optical drive and restart the computer.
             After the chime press and hold down the  "C" key.  Release the key when you see
             a small spinning gear appear below the dark gray Apple logo.
         2. After the installer loads select your language and click on the Continue
             button. When the menu bar appears select Disk Utility from the Utilities menu.
             After DU loads select the hard drive entry from the left side list (mfgr.'s ID and drive
             size.)  Click on the Partition tab in the DU main window.  Set the number of
             partitions to one (1) from the Partitions drop down menu, click on Options button
             and select GUID, click on OK, then set the format type to MacOS Extended
             (Journaled, if supported), then click on the Apply button.
         3. When the formatting has completed quit DU and return to the installer.  Proceed
             with the OS X installation and follow the directions included with the installer.
         4. When the installation has completed your computer will Restart into the Setup
             Assistant. After you finish Setup Assistant will complete the installation after which
             you will be running a fresh install of OS X.  You can now begin the update process
             by opening Software Update and installing all recommended updates to bring your
             installation current.
    Download and install Mac OS X 10.6.8 Update Combo v1.1. You may then open App Store, click on the Purchases icon in the toolbar, and re-download any OS X upgrade you purchased except Mavericks. Since Yosemite has been released the App Store may not let you re-download Mavericks, but it will let you download Yosemite.

  • [solved] Measuring how much time a bash function takes to run?

    Hi there,
    a (hopefully) simple question for the bash gods out there :)
    Lets say i have a script looking like this:
    #!/bin/bash
    some_function() {
    doing something
    some_function
    How can i measure the time (preferably in human-readable form: minutes or even hours) the bash function takes for a run?
    I know about "time", but i want to do it directly inside the script...
    Google tells me nothing, apart from one site where i have to pay for a solution :/
    Thanks for any suggestions
    Jan
    Last edited by funkyou (2008-09-01 13:21:04)

    iphitus@laptop:~$ sh test.sh
    Hi
    Bye
    real 0m10.002s
    user 0m0.000s
    sys 0m0.003s
    iphitus@laptop:~$ cat test.sh
    somefunc(){
    echo "Hi"
    sleep 10
    echo "Bye"
    time somefunc
    Time appears to work within bash scripts too

  • Terminal/bash stalls at password-prompt after sudo-command

    hi,
    under 10.5.2 Terminal lets me type or paste a sudo-command, but then, asking for my root-password, does not react to any inout from keyboard or via paste. What can that be?

    It is normal for nothing to appear on the screen while the password is being typed. Press Enter when you've finished entering it.
    (30698)

  • What do the following SUDO-Commands mean and do?

    Hey Everybody,
    I did google these two commands but I cannot find a straight answer which is understandable for me. Can someone please explain to me in plain English what they do?
    1. "sudo chmod -RN ~"
    2. "sudo chown -R `id -un` ~"
    My second question is: After I have executed these 2 commands, will there be a problem or danger to my system if I won't boot up off the Leopard DVD and click the "Reset" button in the "Reset Home Directory Permissions and ACLs" section? Because this reset seems not possible on my machine.
    Thank you very much for your answers!
    AirMcEnroe

    I'll start off by asking if you have a problem that you are trying to solve, or if you are just having fun with Google? The sudo command is a very dangerous command, and using the -R option allows the computer to multiply your mistakes with amazing speed.
    I did google these two commands but I cannot find a straight answer which is understandable for me. Can someone please explain to me in plain English what they do?
    1. "sudo chmod -RN ~"
    sudo says run the following command as if you were the super user (the all powerful). It will prompt for your password (assuming you are an 'admin' user). You will see nothing while typing the password.
    chmod is used to change file permissions (see "man chmod").
    The tilda ~ says start with your home directory.
    -R says recursively process every file and directory under the specified starting directory (in this case you specified ~ your home directory).
    -N says remove any Access Control Lists (ACL) found.
    Not sure why you want to do this. It seems like a very big hammer and some of those ACLs may be service a valuable function, such as protecting you from shooting yourself in the foot, or enabling specific needed permissions on newly created files, etc...
    And if you happen to fumble finger entering the starting directory ~, you could destroy ACLs outside of your home directory tree and destroy critical OS ACLs.
    Make sure you have a very good full system backup before you take aim at your foot.
    2. "sudo chown -R `id -un` ~"
    chown changes the ownership of files and directories.
    -R says recursively process every file and directory under the specified starting directory (in this case you specified ~ your home directory).
    `id -un` obtains your short username, the `...` says substitute the output from id -un onto the chown command line.
    So this command is going to walk your home directory tree and change the ownership of every file and directory it finds and force you to be the owner.
    Again a very big hammer, and one that if you specify the wrong starting directory will turn your Mac into a paper weight. Make sure you have a very good full backup before you start.
    My second question is: After I have executed these 2 commands, will there be a problem or danger to my system if I won't boot up off the Leopard DVD and click the "Reset" button in the "Reset Home Directory Permissions and ACLs" section? Because this reset seems not possible on my machine.
    By the way, Terminal, Unix, X11, and command line command, ssh, rsync, etc... questions are best asked in the Mac OS X Technologies > Unix Forum
    <http://discussions.apple.com/forum.jspa?forumID=735>

  • HT4103 my sudo command is not working

    Hello, when i type sudo it show bellow message
    Arifur-Rahmans-MacBook-Pro:~ arif$ sudo
    -bash: sudo: command not found
    when i type ls
    Arifur-Rahmans-MacBook-Pro:~ arif$ ls
    -bash: ls: command not found
    Please help me i am not able to work anythings.

    When I said type
    echo $PATH
    I did mean PATH in ALL CAPITALS.  When working on the Unix side of Mac OS X, as weill all Unix systems upper and lower case do matter.
    But from the error message, I can see that somewhere along the way, mongodb (a database package), and the modification of PATH was done incorrectly.
    If you installed MongoDB, AND if the instructions had to modify your .profile (or perhaps .bash_profile), then either their instructions were wrong, or you missed a step, which explains why you can not enter commands are not found
    PATH is a Unix environment variable that contains a colon separate list of directories where the shell will look for commands when you enter them at the command prompt.
    So your choices are delete the offending .profile (or perhaps .bash_profile) and forget about MongoDB, or if you do need MongoDB, then fix your .profile (or .bash_profile) so it has a properly formed PATH environment variable.
    Fixing this would look like
    /bin/ls -a         # this will show you all the files starting with a period (dot) as in .profile or .bash_profile
    /usr/bin/nano .profile
    now in this text editor use the arrow keys, and the delete key to find and delete offending text, then type in the corrected text.  Nano gives you a menu at the botton of the editor with additional commands.  ^O (Control-O) writes out any changes you made.  ^X (Control-X) exits from Nano.
    You want your PATH variable to look like (REMEMBER UPPER/lowercase is IMPORTANT)  ALSO spaces or nospaces are important.
    export PATH="/usr/local/mongodb-osx-x86_64-1.8.2:$PATH"
    NOTICE there is a colon between the MongoDB directory path, and the $PATH.  The $PATH will append your existing PATH to the end of the new PATH environment variable you are setting up.  The entire PATH string is enclosed in double quotes.  ALSO NOTICE, there is only 1 space between export and PATH.  No spaces anywhere else in the line.
    Again, I used .profile as the most likely file name, HOWEVER, your shell will look for 1 of 3 different initialization files starting with
    .bash_profile
    .bash_login
    .profile
    If will use the first file it finds in the above order and stop looking as soon as it finds a match.  So it is important that you edit the correct file.  The
    /bin/ls -a
    command will tell you want leading period filenames exist in your home directory
    I'll also give you one word of caution.  When playing on the Unix side of Mac OS X, and following instructions you do not understand, it is generally wise to have a very recent full backup of your system.  There are some commands that can make your system unusable should you enter them blindly.
    Message was edited by: BobHarris

  • Terminal doesn't understand sudo command

    I am installing MacPorts 1.7.0 from a .dmg file. Following, I set up the environment variables in the .profile file, and tried to use Terminal to update using the sudo port selfupdate command from Terminal.
    This is the result I got:
    -bash: sudo: command not found
    Why is this, and what can I do?

    I think the error refers to the command(s) following "sudo." Were you prompted for your password?
    No, that would be:
    sudo fred
    Password:
    sudo: fred: command not found
    But if the command bash is asked to execute is not found you get
    fred
    -bash: fred: command not found
    So I think he is not finding sudo.
    That makes me think that PATH has been messed up, because sudo is in /usr/bin/sudo which is always in PATH unless it has been messed up. Which makes me think that .profile was properly executed, and that is how PATH got messed up.
    So I would look very closely at .profile and make sure PATH is setup correctly. I would expect it to looks something like:
    export PATH="$PATH:/opt/local/bin"

  • [SOLVED] sudo problem??

    There's an issue with my sudo command. I have installed the package set up my sudoers file properly. Everytime I call sudo it gives me the password prompt but when I type my account's password it says it's INCORRECT. I have no issues logging in or anywhere else.
    So far I have been able to circumvent this issue by using the NOPASSWD: tag in the sudoers file, but I'd really like to pin down the issue.
    Thanks in advance.
    Edit: Reinstalling pambase does the trick.
    Last edited by vasuman (2012-06-26 18:46:00)

    *cough* ...search function... *cough*
    https://bbs.archlinux.org/viewtopic.php?id=143487
    https://bbs.archlinux.org/viewtopic.php?id=142729
    https://bbs.archlinux.org/viewtopic.php?id=142720
    https://bbs.archlinux.org/viewtopic.php?id=142941
    https://bbs.archlinux.org/viewtopic.php?id=143335

  • Getting a fatal relocation error while using a sudo command.

    I am getting the following error while trying to execute a sudo command:
    ld.so.1: sudo: fatal: relocation error: file /usr/local/bin/sudo: symbol closefrom: referenced symbol not found
    the sudo version I use is: 1.6.8p9
    the SUNWcsu package that contains the ld.so.1 library is version: 11.8.0,REV=2000.01.08.18.12
    any ideas?

    Just had the same error
    ld.so.1: sudo: fatal: libintl.so.8: open failed: No such file or directory
    Killed
    was solved by adding the Dependances
    libintl-3.4.0-sol10-sparc-local.gz Libintl is used with gettext and is needed by a few programs when libintl in not in /usr/lib - installs in /usr/local/lib. The 3.4.0 package number indicates that this provides /usr/local/lib/libintl.so.3.4.0 (and also the new /usr/local/lib/libintl.so.8.0.2). Dependencies: libiconv and to have /usr/local/lib/libgcc_s.so.1 and /usr/local/lib/libstdc++.so.6, either the libgcc-3.4.6 or gcc-3.4.6 packages.
    http://www.sunfreeware.com/indexsparc10.html

  • [DIS-SOLVED] Sudo hangs after a few uses

    I've been searching around for this for some time, but haven't found any enlightenment yet.
    Basically, after rebooting I can use sudo a few times (usually 3) successfully. After that, any sudo command just hangs. Interestingly, "sudo -k" still returns normally, but "sudo -v" hangs. It is worth noting that sudo gets as far as prompting me for my password before hanging.
    Background - possibly useful:
    I've had arch running for a few months now, and this just started happening yesterday, when I left my machine running overnight doing a large dd to an external drive as described here: https://wiki.archlinux.org/index.php/Di … _hard_disk . I woke up, found that the i/o was all finished (I could tell because I was using pv to monitor it), but the command ( which was "sudo dd if=/dev/sda conv=sync,noerror bs=32M | pv -pbert | gzip -c > /run/media/jimbo/Backup2/sda_82513.img.gz") hadn't returned and wasn't responding to SIGINTs. The hanging behavior started here, and I wasn't able to kill the process or unmount my external cleanly. I'm not sure exactly what I did then, but I'm pretty sure I just hard-rebooted my machine, and I've been seeing this behavior ever since.
    Any pointers or advice would be greatly appreciated. I'll post any config files you guys are interested in, with PII redacted.
    Last edited by jmagnare (2013-08-30 21:05:05)

    Thanks for the warm welcome! I'm having a blast using arch so far.
    So I restored from the dd that I had done, and things are working fine now. I'm not sure what I should do with this thread: should I mark it solved? I didn't actually discover the cause of the problem, so that doesn't seem right.
    To answer your questions:
    1. I may have had one of the partitions on sda mounted. Is this likely to have caused what I saw?
    2. pv, which I just discovered, allows you to see the progress of data through a pipeline. It's pretty neat. The p, b, e, r, and t flags should turn on the progress bar, byte counter, ETA timer, rate counter, and timer, respectively. After looking at the man page, it appears that this is actually the default behavior. So I could have just used pv with no options.
    Last edited by jmagnare (2013-08-29 17:03:00)

Maybe you are looking for

  • The operation could not be completed because an item with the name xyz already exists

    I am trying to make a click and drag backup on an external FAT 32 drive to compliment my Time Machine backup (long story) and I've done this each time by dragging my critical folders into the drive. I get a message asking me to stop, replace or skip,

  • Can't save pdf in cs5 on mac, why?

    Anyone?

  • Scheduling updatable materialized view

    Hi everybody, As you may know I have a solution in which I have 5 sites .One master site with 4 updatable materialized view sites. I want to know that is it correct if I dont set up schedule push to run periodically and set it up to do continuous pus

  • IPhone 3GS screen shakes while scrolling

    Hi everyone! I have an iPhone 3GS. Everytime I try to search for songs or browse the net, I have to scroll down and up and zoom in and out like everyone else does. Now the problem is when I do this, the screen starts to shake. Can anyone find a solut

  • Quantity Restriction in a sales order

    Hi Gurus, How can we ensure that the quantity in a sales order is not reduced after it has been copied from a quotation, the quantity can be reduced but not incresed. Points will be rewarded. Rgds, Ravi