简体   繁体   中英

How to check file owner in linux

How to check file owner in linux

i am trying to run this bash file

#!/bin/bash
uname2=$(ls -l $1 | awk '{print $3}');
if [ $uname2 == $USER ]
then echo owner
else echo no owner
fi

it gives error ==' unary operator expected. what is wrong? ubuntu server 10.04.

Use = not == for comparison. The test(1) man page says:

STRING1 = STRING2
       the strings are equal

I'd also recommend using stat to find out the owner instead of some ls hacks. Some double quotes and an extra x would also be nice.

#!/bin/bash
uname2="$(stat --format '%U' "$1")"
if [ "x${uname2}" = "x${USER}" ]; then
    echo owner
else
    echo no owner
fi

Try running your script with bash -x and you can see exactly what's going on. I bet that one of your variables is empty. You can protect against this by quoting the variables, like this:

if [ "$uname2" == "$USER" ]

You forgot to put " next to variables.

uname2=$(ls -l $1 | awk '{print $3}');
if [ "$uname2" == "$USER" ]
then echo owner
else echo no owner
fi

You want:

#!/bin/bash
uname2=$(ls -ld $1 | awk '{print $3}' | tail -1);
if [ "$uname2" == "$USER" ]
then echo owner
else echo no owner
fi

Your output contains multiple lines, and the first line is going to be blank. So snag the last one with tail . Also, as others have pointed out, the best practice is to use quotes in your arguments. That way you won't end up with an incomplete command in the case of a blank variable, etc.

You also want to include d in the argument list to ls so that this works properly with directories. (checks if the directory has an owner) Otherwise you'll just get the last file in the directory.

There is one simple option available to check whether file is owned by the use or not, who is executing current script.

if [[ -O "$0" ]]; then
    echo "owner"
else
    echo "no owner"
fi

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM