2012-08-30 189 views
3

我学习bash和希望你们能帮助我发生了什么事情与下面的脚本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 

它看起来对我说,如果我改变了也没关系文件的权限,因为输出始终是相同的

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

文件1可以为空或不是静态输出是一样的,做同样的测试

任何人能向我解释什么是wron G?

感谢

BTW这里的脚本是compare3 Ubuntu的解开了书2011版(图书网站http://ubuntuunleashed.com/)的233页上的修改版本

回答

4

file1变量是不确定的。

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

2

更改为$1$file1变量或添加在脚本的开头如下(将#后/斌/庆典!):

set file1=$1 

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

./script.sh file 
+0

设置仅用于tcsh还是bash? – murpholinox

+0

是的,'set'它也可以在bash中使用 – higuaro

2

或删除DOLAR标志,或更换$file1$1并使用脚本./script.sh file1

3

这是所有测试都成功的原因:自变量为空,你会得到

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

因为你使用单支架,庆典只看到一个测试条件的单个词。当测试命令只看到一个参数时,如果该单词不是空的,则结果为真,并且在每种情况下,该单词包含2个字符。

当然,修正是声明变量。此外,您应该使用bash的条件结构

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

当双支架使用,bash将看到的情况2分的话,即使变量为空或空。