简体   繁体   English

从Bash脚本中的文件参数打印权限

[英]Print permissions from file arguments in Bash script

I'm having trouble reading the permissions of file arguments. 我无法读取文件参数的权限。 I looks like it has something to do with hidden files but I'm not sure why. 我觉得它与隐藏文件有关,但我不知道为什么。

Current Code: 现行代码:

#!/bin/bash

if [ $# = 0 ]
then
    echo "Usage ./checkPerm filename [filename2 ... filenameN]"
    exit 0
fi

for file in $@
do
    ls -l | grep $file | cut -f1 -d' '

    # Do Something

done

I can get the permissions for each input, but when a hidden file is run through through the loop it re-prints the permissions of all files. 我可以获得每个输入的权限,但是当通过循环运行隐藏文件时,它会重新打印所有文件的权限。

-bash-4.1$ ll test*
-rw-r--r-- 1 user joe 0 Nov 11 19:07 test1
-r-xr-xr-x 1 user joe 0 Nov 11 19:07 test2*
-r--r----- 1 user joe 0 Nov 11 19:07 test3
-rwxr-x--- 1 user joe 0 Nov 11 19:07 test4*
-bash-4.1$ ./checkPerm test*
-rw-r--r--
-rw-r--r--
-r-xr-xr-x
-r--r-----
-rwxr-x---
-r--r-----
-rw-r--r--
-r-xr-xr-x
-r--r-----
-rwxr-x---
-bash-4.1$

What is going on in the loop? 循环中发生了什么?

It's your grep: 这是你的grep:

ls -l | grep 'test2*'

This will grep out anything starting with test since you're basically asking for anything starting with test that might end with 0 or more 2 s in it, as specified by the 2* . 这将从test开始,因为你基本上要求以test开始的任何东西,可能以0或更多2秒结束,由2*指定。

To get your intended result, simply remove your loop and replace it with this: 要获得预期的结果,只需移除循环并将其替换为:

ls -l "$@" | cut -d' ' -f1

Or keep your loop, but remove the grep: 或保持你的循环,但删除grep:

ls -l $file | cut -d' ' -f1

Also, technically, none of those files are hidden. 此外,从技术上讲,这些文件都不会被隐藏。 Hidden files in bash start with . bash中的隐藏文件以. , like .bashrc . ,像.bashrc

When you do the ls -l inside the loop and then grep the results, if there are files that contain test1 in the name, but not at the start, they are selected by the grep , giving you extra results. 当您在循环中执行ls -l然后grep结果时,如果文件中包含名称中的test1但不在开头,则grep会选择它们,从而为您提供额外的结果。 You could see that by doing: 您可以通过以下方式看到:

ls -l | grep test

and seeing that there are many more entries than the 4 you get with ls -l test* . 并且看到有更多的条目,而不是你用ls -l test*获得的4个条目。

Inside your loop, you should probably use just: 在你的循环中,你应该只使用:

ls -ld "$file" | cut -d' ' -f1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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