I have a bash script that is supposed to take some arguments and then run in a different user: test.sh#!/bin/bashsudo su user2 <<'EOF'echo $1EOFHowever it prints blank:  $ ./test.sh hahaI understand that it is because environment variable are reset(?). How can I pass this argument? Security wise I've heard I should not disable environment resetting. The only way comes to my mind to solve this is writing $1 to a file and then reading it back again by user2. But I guess there should be a much better way.
Pass arguments to a command run by another user
shell;shell script;sudo;su;arguments
If you want the entire script to run as another user, my usual technique for doing this is adding something similar to the following to the very top of the script:target_user=fooif [ $(whoami) != $target_user ]; then  exec sudo -u $target_user -- $0 $@fiNote that I use sudo here and not su. su makes it stupidly difficult to pass arguments properly, while sudo does not have this issue.If you only want to run a small bit of code, you can alternatively do something such as:target_user=foosudo -u $target_user sh -s $@ <<'EOF'  echo $@EOFThis will launch sh, pass it the current script's arguments, and then execute the script provided via the heredoc.