【问题标题】:Get file owner name whit the use of ls and cut command使用 ls 和 cut 命令获取文件所有者名称
【发布时间】:2018-11-29 10:58:43
【问题描述】:

我目前正在尝试使用以下函数创建一个检索文件所有者名称的函数:

OWNER_IDX=3
fileowner=""

#Gives file owner name. Takes the file name as an argument
function getfileowner()
{
    fileowner=`ls -l | grep $1 | cut -f $OWNER_IDX -d " "`
    echo $fileowner
}

为了验证我的函数究竟做了什么,我创建了一个测试函数:

function testgetfileowner()
{
    for file in `ls`
    do 
        getfileowner $file
        echo "$file belongs to $fileowner"
    done
}

但是当我执行我的脚本时,我得到了这个输出:

exemple_gz.gz belongs to 
exemple_tar.tar belongs to 
exemple_tgz.tgz belongs to 
exercice_10.sh belongs to 
exercice_8.sh belongs to 
INFOH304 belongs to 
lipap.sh belongs to 

我测试线

fileowner=`ls -l | grep $1 | cut -f $OWNER_IDX -d " "`

在终端上如下:

ls -l  | grep exemple_gz.gz | cut -f 3 -d " "

而且效果很好。我做错什么了?提前致谢。

【问题讨论】:

  • 为什么不直接使用stat -c %U $1?而且即使有你的代码,grep 阶段也没用,你可以直接做ls -l $1
  • 也代替for file in `ls` for file in *。它更安全、更短。
  • @Geoffroy 我不允许使用我还没有学过的任何命令。但是感谢您的建议,这更容易。我使用grep 阶段的原因是因为当$1 是文件夹时使用ls -l $1 不能正常工作。
  • @genkidesuka ls -ld 就是这种情况,所以它列出了目录本身而不是它的内容
  • 我质疑一个无法为目前提供的材料提供适当作业的课程。

标签: bash shell


【解决方案1】:

$fileowner 在您的测试中从未设置为任何值,您应该返回getfileowner 中的值。

另外,正如我在cmets中所说,您可以直接使用stat -c %U filename获取用户名。

您的函数中还有另一个问题:ls -l | grep $1 可以匹配多个文件并且是多余的,而 ls -dl $1 直接执行您想要的操作,-d 允许列出目录本身,而不是其内容。

【讨论】:

  • @Geoffoy 我用echo "`ls -ld $1 | cut -f $OWNER_IDX -d " ""`` 返回了getfileowner() 中的值,并按照你的建议在我的测试函数中检索了它,如下echo "$file belongs to $(getfileowner $file)"。它有效。非常感谢。
  • 这不是返回值,你只是在标准输出上打印一些东西并在另一边捕获它......但是,它也可以这样工作,毕竟。
【解决方案2】:

this 中所示,另一种解决方案是在标准输出上打印,而不是返回值并通过命令替换来捕获它。

#Gives owner name. Takes the file name as an argument
function getfileowner()
{
    echo "`ls -ld $1 | cut -f $OWNER_IDX -d " "`"
}
function testgetfileowner()
{
    for file in *
    do 
        echo "$file belongs to $(getfileowner $file)"
    done
}

【讨论】:

  • echogetfileowner 中不需要,因为这些命令无论如何都会打印在标准输出上。
猜你喜欢
  • 1970-01-01
  • 2019-10-05
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多