How to use the "-" character in grep?

I was hoping to use grep to verify and verify that the permissions in the file are set correctly ...

I know that the situation below is probably not ideal and not as brief as it could be, but I follow certain properties such as owner name and permissions ...

I was going to use something like this:

cd ~/Desktop

if [ `ls -a | grep My File.txt | wc -l` -eq 1 ];
then
echo "My File.txt Exists"

    MYPERMISSIONS=`ls -l My File.txt`

    if [ `$MYPERMISSIONS | grep $"\-rwxr\-xr\-x" | wc -l` -eq 1 ];
        then
        echo "Permissions are correct for My File.txt"
    fi

    if [ `$MYPERMISSIONS | grep $"\-rwxr\-xr\-x" | wc -l` -eq 0 ];
        then
        echo "Permissions are NOT correct for My File.txt"
    fi

    if [ `$MYPERMISSIONS | grep root | wc -l` -eq 1 ];
    then
        echo "Owner is correct for My File.txt"
    fi

    if [ `$MYPERMISSIONS | grep root | wc -l` -eq 0 ];
    then
        echo "Owner is NOT correct for My File.txt"
    fi
fi

if [ `ls -a | grep My File.txt | wc -l` -eq 0 ];
then
echo "My File.txt does NOT Exist"
fi

it looks like grep doesn't want to look for the "-" character ...

any way around this?

Thank!

+3
source share
5 answers

, : -, grep; ; carat ^ ( , - ).

:

if [ `echo "$MYPERMISSIONS" | grep "^-rwxr-xr-x" | wc -l` -eq 1 ]
+3

, '-' . , grep -e, , .

+5

grep :

if [ ls -a | grep 'My File\.txt' | wc -l -eq 0 ]; then echo "My File.txt does NOT Exist" fi
+2

, ? , :

ls -l | grep "drwxr-xr-x" 
+2

script - , ( $MYPERMISSIONS, grep, escape- , ). , - ls output. , , "Not My File.txt" - ls | grep | wc "My File.txt Exists", ( , "My File.txt" ). -, , "notroot" - script , root, ls "root". -, , "-rwxr-xr-x" ( , , )...

, , , -e . , stat .

Finally, instead of using redundant commands if(if the file exists ... followed by if the file does not exist ...), use a sentence elsefor one command if. After fixing all of this (and a little minor cleanup, for example by putting the file name in a variable), here is how I rewrote the script:

cd ~/Desktop
filename="My File.txt"

if [ -e "$filename" ];
then
    echo "My File.txt Exists"

    if [ "$(stat -f "%Sp" "$filename")" = "-rwxr-xr-x" ]; then
        echo "Permissions are correct for My File.txt"
    else
        echo "Permissions are NOT correct for My File.txt"
    fi

    if [ "$(stat -f "%Su" "$filename")" = "root" ]; then
        echo "Owner is correct for My File.txt"
    else
        echo "Owner is NOT correct for My File.txt"
    fi

else
    echo "My File.txt does NOT Exist"
fi
+2
source

All Articles