【问题标题】:compare file permissions between 2 files in bash比较bash中2个文件之间的文件权限
【发布时间】:2016-06-05 18:16:05
【问题描述】:

我正在尝试比较 2 个文件的权限,但似乎无法获得正确的结果。谁能帮忙。

act= stat -c "%a" a
bac= stat -c "%a" b

echo "$act"  # returns correctly eg 777, not sure if this is a string or no.
echo "$bac"  # returns correctly as above


if [[ "$act"="$ghi" ]];
then 
   echo "Correct"
else
   echo "Difference"
fi

这是我目前得到的 说属性是一样的 1.第一次a=777和b=777 2. 第二次a=222 and b=777

#!/bin/bash

active= stat -c "%a" a
backup= stat -c "%a" b


echo "$active"
echo "$backup"

if [[ "$active" = "$backup" ]];
then 
        echo "Properties are The Same"
else
        echo "Properties are Different"
fi

这是我得到的输出

sandbox-computer work # ./compareFiles_02.sh
777
777

属性相同

sandbox-computer work # chmod 222 a
sandbox-computer work # ./compareFiles_02.sh
222
777

属性相同

【问题讨论】:

标签: bash syntax


【解决方案1】:
act=$(stat -c "%a" file1)
bac=$(stat -c "%a" file2)

if [[ "$act" = "$bac" ]] # whitespaces added, $ghi replaced by $bac
then 
   echo "Correct"
else
   echo "Difference"
fi

【讨论】:

  • #!/bin/bash active= stat -c "%a" a backup= stat -c "%a" b echo "$active" echo "$backup" if [[ "$active " = "$backup" ]];然后 echo "Properties are the Same" else echo "Properties are different" fi 这是我得到的输出 sandbox-computer work # ./compareFiles_02.sh 777 777 Properties are the Same sandbox-computer work # chmod 222 a sandbox-computer work # sandbox-computer work # sandbox-computer work # ./compareFiles_02.sh 222 777 属性相同
  • @MMouse 你需要命令替换:active=$(stat -c "%a" a), ... 不是active= stat-c "%a" a
【解决方案2】:

将 if 写成if [ "$act" = "$bac" ];(推荐)或if [ "$act" == "$bac" ](不推荐)。

参考:http://tldp.org/LDP/abs/html/comparison-ops.html

【讨论】:

  • 为什么要提一些不推荐的东西?不解释为什么
  • tldp 指南已经过时,在某些情况下完全是错误的。强烈推荐使用 Greg 的 Bash 指南。
  • @andlrc == 比较运算符在双括号测试中的行为与在单括号中的行为不同。答案中的链接。
  • @MMouse = 之间的空格应如答案所示。也请参考链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-24
  • 2013-06-06
  • 2014-11-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多