I have a script that copies files between servers. I am using the lsof command to make sure that the file is not being written to before being moved. The user running the script and the user writing to the file are different, so I need to sudo to the file owner. Here is the relevant line in the sudoers file :
userA ALL=(userB:userB) NOPASSWD: ALL
In the main script (ran as userA), I have tried calling sudo then the subscript containing the lsof command:
sudo su - userB -c 'source ./getOpenFiles.sh'
getOpenFiles.sh has this one line:
#!/bin/bash
lsofResult=$(/usr/sbin/lsof "${sourcePath}")
I have also tried calling the subscript:
source ./getOpenFiles.sh
Then have the first line of the subscript be the sudo:
#!/bin/bash
sudo su - banjobs
lsofResult=$(/usr/sbin/lsof "${sourcePath}")`.
Neither solution is working.
sudo su - banjobs, the next command doesn't run until after yoursudo sufinishes and exits, and nothing left is running asbanjobs.lsofResultasbanjobs.su -c 'source somescript', thensomescriptis run bysh, notbash, no matter what its shebang says. And if yourshdoesn't supportsource, then it doesn't run at all. (The POSIX-compatible way to writesourceis. somescript, notsource somescript).source. (Though if you expectsourceto result in the variable being set in the parent shell -- that is, the shell that's running yoursudocommand, that won't ever work, sincesudois itself a subprocess -- the point ofsourceis to do something directly in your current shell process; if you do anything in a subprocess, that entirely defeats the point)..bashextension, rather than a.shextension -- that way it's more obvious to readers that the code isn't intended to be compatible with POSIX sh, but specifically is only safe to source into interpreters with bash extensions. (Not that it matters for the specific code you gave here, which other thansourceis POSIX-sh-compatible, but consider it a best-practices note). By contrast, for commands intended to be executed rather than sourced, it's more appropriate not to have any file extension at all.