0

I run a bash python command as current user, by doing this:

su $USER -c 'python3 -m site --user-site'

This works properly and prints the following:

/Users/standarduser7/Library/Python/3.6/lib/python/site-packages

I want to assign this output to a variable, so I'm using "$(command)":

target="$(su $USER -c 'python3 -m site --user-site')"

At this point, the OSX terminal hangs and has to be killed. Using backticks instead of "$(command)" leads to same result.

However, if I run the command without user, everything works as it should: target="$(python3 -m site --user-site)" echo target

output: /Users/standarduser7/Library/Python/3.6/lib/python/site-packages

How can I assign the output from a command run as the current user to a variable?

1 Answer 1

0

I don’t think it’s hanging; I think it’s showing a blank (prompt-less) command-line and is waiting for input. When I key in the user password, it returns this result:

Password:/Users/CK/Library/Python/2.7/lib/python/site-packages

and this is what ends up being stored in the target variable. A quick parameter substitution can rectify this anomalous output:

target=${target#*:}

The other solution (credit given to this answer) is to create a file descriptor as a copy of stdout, then tee the command to the copy, which then allows stdout to be piped to grep in order to process the output:

exec 3>&1 # create a copy of stdout

target=$(su $USER -c "python -m site --user-site" | tee /dev/fd/3 | grep -o '\/.*')

exec 3>&- # close copy
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.