I wrote a bash script to verify various configs on a system, but I am getting different results depending on whether it is run from the command line directly or from the script. Here is the command:
bt_discoverable=$(system_profiler SPBluetoothDataType | grep Discoverable)
If I disable discoverable on the bluetooth and then echo the variable on the command line I get the expected result:
Discoverable: No
But if I echo it immediately after running the same command from a bash script, I get
Discoverable: Yes
The script does elevate its privileges through an internal sudo function, so I commented the block for that function out and ran the script again. This time, things worked as they should. Here is the elevation function:
RunAsRoot()
{
if [[ "${USER}" != "root" ]] ; then
echo
echo
echo "*** Type the password for ${USER} and press ENTER ***"
echo
sudo $1 && exit 0
fi
}
RunAsRoot $0
This function is the first thing the script runs, so the code position is a problem.
Why does running in an elevated privilege (sub)shell cause this issue? Is the problem Terminal, Bash, or something else I'm ignorant of?
Best Answer
The difference comes from the change in shell environment once elevated. I'm not sure how you would write a script that would account for this change easily, but the answer to my original question is that you need to be aware of such differences when you elevate privileges.
Thanks to "thankyour" for this lead. I finally posted this as an answer since they didn't for some weeks.