I’ve made a bash script which is executed as root and must verify the existence of a file in the Desktop of an user. Here is the code:
if [ -e /Users/*/Desktop/file ]; then
....
The fact is if there are multiple users in /Users/, and that the file is not present in the first user (by alphabetical order) but in one of the others, it will fail.
So to resolve the issue, I thought this was good:
if [ -e ~/Desktop/file ]; then
....
but there, as the script is executed as root, ~/Desktop/ is /private/var/root/Desktop instead of /Users/my_user/Desktop .
I’m not very at ease for the moment with bash so I hope you will help me to resolve this issue ! Thanks !
You could use a for loop in bash to test for each user’s home directory in turn, e.g.:
The
/Users/*is expanded into/Users/alice /Users/bob /Users/charles(or whatever) and then$dis given the value of each of those in turn inside the loop. Obviously you can replace theechostatments with whatever you want to do in either case.The bash manual’s section on looping constructs, including for loops, is here – that might not be the best place to start, but you can find plenty of examples with Google.
One thing to note about this answer is that if you’re being strict, a user’s home directory doesn’t have to be called /Users/username – strictly speaking you need to look in
/etc/passwdto find all users and their corresponding home directories. However, for what you want to do, this might be enough.Update 1: It sounds from the comment below as if you want to take an action if no file matching
/Users/*/Desktop/fileexists for any user. This sounds surprising to me, but if you really want to do that, you could use one of the recipes from this other Stack Overflow question, for example:Update 2: Your comments on Dennis Williamson’s answer indicate that this script is expected to be run by non-root users on this machine. If that’s the case then I think his suggestion in the comments is the right one – you just want to test:
… and then you just just need to make sure you test it as a non-root user.