3

我正在学习 bash,希望你们能帮助我了解以下脚本的情况

#!/bin/bash

#primer if
if [ -f $file1 ]; then
        echo "file1 is a file"
else
        echo "file1 is not a regular file"
fi
#segundo if
if [ -r $file1 ]; then
        echo "file1 has read permission"
else
    echo "file1 doesnot have read permission"
fi
#tercer if
if [ -w $file1 ]; then
        echo "file1 has write permission"
else
    echo "file1 doesnot have write permission"
fi
#cuarto if
if [ -x $file1 ]; then
        echo "file1 has execute permission"
else
    echo "file1 doesnot have execute permission"
fi

在我看来,如果我更改文件权限并不重要,因为输出总是相同的

fmp@eva00:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file
file1 has read permission
file1 has write permission
file1 has execute permission
fmp@eva00:~/Books/2012/ubuntu_unleashed$ ll file1
-rw-r--r-- 1 fmp fmp 0 Aug 30 13:21 file1
fmp@eva00:~/Books/2012/ubuntu_unleashed$ chmod 200 file1
fmp@eva00:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file
file1 has read permission
file1 has write permission
file1 has execute permission
fmp@eva00:~/Books/2012/ubuntu_unleashed$ ll file1
--w------- 1 fmp fmp 0 Aug 30 13:21 file1
fmp@eva00:~/Books/2012/ubuntu_unleashed$ chmod 000 file1 
fmp@eva00:~/Books/2012/ubuntu_unleashed$ ll file1
---------- 1 fmp fmp 0 Aug 30 13:21 file1
fmp@eva00:~/Books/2012/ubuntu_unleashed$ ./script.sh 
file1 is a file
file1 has read permission
file1 has write permission
file1 has execute permission

file1 可以为空或不为空,但输出仍然相同,进行相同的测试

有人可以向我解释什么是错的吗?

谢谢

顺便说一句,这里的脚本是 ubuntu unleashed book 2011 版第 233 页上 compare3 的修改版本(图书网站http://ubuntuunleashed.com/

4

4 回答 4

4

file1变量未定义。

您应该在脚本的开头添加file1="file1"

于 2012-08-30T20:11:08.350 回答
3

这就是您所有测试都成功的原因:由于变量为空,您得到

if [ -f  ]; ...
if [ -r  ]; ...
if [ -w  ]; ...
if [ -x  ]; ...

因为您使用的是单括号,所以 bash 只能看到一个单词来表示测试条件。当测试命令只看到一个参数时,如果单词不为空,则结果为真,并且在每种情况下,单词都包含 2 个字符。

当然,解决方法是声明变量。此外,您应该使用 bash 的条件构造

if [[ -f $file ]]; ...
if [[ -r $file ]]; ...
if [[ -w $file ]]; ...
if [[ -x $file ]]; ...

当使用双括号时,即使变量为空或 null,bash 也会在条件中看到 2 个单词。

于 2012-08-30T23:02:23.523 回答
2

在脚本开头(#!/bin/bash 之后)更改$file1变量或添加以下内容:$1

set file1=$1

所以你可以像这样调用你的脚本:

./script.sh file
于 2012-08-30T20:12:41.040 回答
2

或删除美元符号,或替换$file1$1并将脚本用作./script.sh file1

于 2012-08-30T20:13:17.747 回答