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 /root
drwx-----x 2 root root 4096 Apr 3 04:55 /root
user@host:~$ [ -e /root/1.txt ] && echo yes
yes
user@host:~$ ls /root
ls: cannot open directory /root: Permission denied
A 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.
1.txt
, it's that root's home directory isn't world-readable and really shouldn't be. – Shadur-don't-feed-the-AI Apr 18 '16 at 04:51sudo test
? – Jeff Schaller Apr 18 '16 at 10:06