Bash – How to change the command to run without superuser privilleges but with the changed limit value

bashsudo

From https://stackoverflow.com/a/17483998/156458

while you do need to be root to raise the limit to 65535, you probably
don’t want to run your program as root. So after you raise the limit
you should switch back to the current user.

To do this, run:

sudo sh -c "ulimit -n 65535 && exec su $LOGNAME"

From Why does the following way not change core file limit size?, I would like to do the following:

I should put the command which uses the new limit value inside the
shell executed by sudo

e.g.

$ sudo sh -c "ulimit -c 1024 && sleep 100"
^\Quit
$ ls
core

ulimit -c 1024 needs super user privilleges, while sleep 100 doesn't.

How can I change my command so that sleep 100 doesn't run with superuser privilleges but with the changed limit value?


Update:

I tried the command from the replay by Hauke, and suspected the reason of its failure is because sudo -c doesn't work on Linux, and still wonder what his intention of using sudo -c was:

$ sudo sh -c "ulimit -c 1024 && sudo -u nobody -c \"sleep 100\""
[sudo] password for t: 
usage: sudo -h | -K | -k | -V
usage: sudo -v [-AknS] [-g group] [-h host] [-p prompt] [-u user]
usage: sudo -l [-AknS] [-g group] [-h host] [-p prompt] [-U user] [-u user] [command]
usage: sudo [-AbEHknPS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] [VAR=value] [-i|-s] [<command>]
usage: sudo -e [-AknS] [-r role] [-t type] [-C num] [-g group] [-h host] [-p prompt] [-T timeout] [-u user] file ...

I have tried the following two commands, but the whole commands return immediately instead of running sleep 100. Why?

$ sudo bash -c "ulimit -c 1024  && exec su $LOGNAME && sleep 100"
$ sudo bash -c "ulimit -c 1024  && exec bash -c \"su $LOGNAME;  sleep 100\" "
$ 

The following command creates a core file. But does the second sudo not clear up the limits by default? I heard sudo often or always clean up execution environment?

$ ulimit -c
0
$ sudo sh -c "ulimit -c 1024 && sudo -u nobody sleep 100"

I found http://jdebp.eu./Softwares/nosh/guide/ulimit.html from https://unix.stackexchange.com/a/446619/674, and wonder how I could achieve similar things using shell scripts:

Most shells have a built-in ulimit command that does not chain and that has additional interactive functionality. See the manual for each individual shell for its built-in command. This command is more commonly used with exec(1) and nosh(1).

Thanks.

Best Answer

sudo sh -c "ulimit -c 1024 && sudo -u nobody -c \"sleep 100\""
Related Question