If you don't want to be challenged every time for your password then I'd recommend setting it to NOPASSWD
in your /etc/sudoers
file rather than hardcode your password in your logins. At least this way your primary login's password will remain intact and not be completely exposed in your .bashrc
.
To make this change run the command sudo visudo
, and change your user accounts entry to something like this:
userX ALL=(ALL) NOPASSWD: ALL
I get the same behaviour with:
sleep 1 && true < /dev/tty &
read var
sudo
opens /dev/tty
to query the current foreground process group, that causes the read()
system call made by bash's read
to return with EAGAIN with Ubuntu 18.04's Linux kernel 4.15.0-45-generic and 4.18.0-14-generic at least causing the read
utility to return with that error.
That seems to be caused by a bug in recent versions of the Ubuntu variants of the Linux kernel. I can't reproduce it on Solaris nor FreeBSD, nor in any version of Linux on Debian (though I can reproduce it if I boot Debian on Ubuntu's 4.18 kernel).
https://bugs.launchpad.net/ubuntu/+source/linux-signed-hwe/+bug/1815021 seems to be another manifestation of that bug.
That's introduced by https://lkml.org/lkml/2018/11/1/663 which ubuntu backported to both its 4.15 and 4.18 kernels at least. But Ubuntu had not backported another change that fixes a regression introduced by that patch until 2 hours ago.
4.18.0-15-generic has now landed in the Ubuntu repositories and fixes the issue. I suppose the one for 4.15 will follow shortly.
ksh93
doesn't have the problem for that same code as its read
builtin uses select()
first to wait for input, and select()
doesn't return when the other process opens /dev/tty
.
So here you could use ksh93
instead of bash
or wait for the fixed kernel or go back to 4.15.0-43 until 4.15.0-46 is released.
Alternatively, you could use zsh
which has builtin support for changing uids (via the EUID/UID/USERNAME special variables) provided you start the script as root
so you wouldn't need to run sudo
within the script (it's also potentially dangerous to extend the life of the sudo token longer than the user would expect).
Best Answer
If it wasn't a bash script but a regular application, you would give ownership of it to root and set the setuid bit on the application. Then upon execution, the effective user the application is running under is root. Due to security concerns however this is in many systems prohibited for shell scripts. This question here on unix.stackexchange.com does handle ways how to overcome this.