bash linux下如何查看文件所有者

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22381983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:54:11  来源:igfitidea点击:

How to check file owner in linux

linuxbashshell

提问by Ilqar Rasulov

How to check file owner in linux

linux下如何查看文件所有者

i am trying to run this bash file

我正在尝试运行这个 bash 文件

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

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

它给出了预期的错误 ==' 一元运算符。怎么了?Ubuntu 服务器 10.04。

回答by Cristian Ciupitu

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

使用===进行比较。该试验(1)手册页说:

STRING1 = STRING2
       the strings are equal

I'd also recommend using statto find out the owner instead of some lshacks. Some double quotes and an extra xwould also be nice.

我还建议使用stat来找出所有者而不是一些ls黑客。一些双引号和额外的x也很好。

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

回答by larsks

Try running your script with bash -xand 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:

尝试运行您的脚本,bash -x您可以确切地看到发生了什么。我敢打赌你的变量之一是空的。您可以通过引用变量来防止这种情况,如下所示:

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

回答by AloneInTheDark

You forgot to put "next to variables.

你忘了把"旁边的变量。

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

回答by Kaushal

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

有一个简单的选项可用于检查文件是否为正在执行当前脚本的用户所有。

if [[ -O "##代码##" ]]; then
    echo "owner"
else
    echo "no owner"
fi