My OS is Ubuntu 14.04 LTS.I got a file /root/1.txt, and logged in with 'yu', who doesn't have read permission on this file.When I use the code if [ -e /root/1.txt ] , it returns false.I know I can use su - root to change user and get the right result.My question is: How can I do this without su - root? Is there a way to solve this situation with sudo?I have solved this situation with testsudo test -e /root/1.txt &&echo the file is exist ||echo the file isn't exist
How can I test if a file in /root exists without su to root?
shell;files;root
It is apparent that the /root directory on your system does not have (at least) 'execute' permisions for the user 'yu', either through group membership or the 'other' bits. Thus, 'yu' cannot list the contents of the /root directory in order to determine if /root/1.txt exists or not.For further description of file and directory permissions (in Linux, as you've mentioned Ubuntu), see:Execute vs Read bit. How do directory permissions in Linux work?If you are unwilling to change the permissions on /root, then you need to escalate your own (well, test's) privileges in order to read the directory. Since [ is a real program (/usr/bin/[) as well as a shell built-in, you can use sudo: sudo [ -e /root/1.txt ] && echo yes || echo no. (Contrast with [[ which is only built-in, not an external program).If you are willing to change the permissions on /root, one minimal change would be to open up 'other' permissions to add the 'execute' bit (sudo chmod o+x /root, for example). This prevents general listing of the directory, but enables you to check about specific files:user@host:~$ ls -ld /rootdrwx-----x 2 root root 4096 Apr  3 04:55 /rootuser@host:~$ [ -e /root/1.txt ] && echo yesyesuser@host:~$ ls /rootls: cannot open directory /root: Permission deniedA variation on 'other+execute' would be 'group+execute' where you add execute permissions to the group and change the group of /root to one that 'yu' is a member of.Long story short, this statement:When I use the code if [ -e /root/1.txt ] , it returns false. I know I can use su - root to change user and get the right result.has a misleading use of the word right. Filesystems permissions dictate how test behaves. It doesn't matter if you know that the file exists; it matters whether the program has the permissions to see the file.