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 edition (書籍サイトhttp://ubuntuunleashed.com/ )の 233 ページにある compare3 の修正版です。

4

4 に答える 4

4

file1変数は定義されていません。

スクリプトの先頭に追加する必要がありますfile1="file1"

于 2012-08-30T20:11:08.350 に答える
3

これが、すべてのテストが成功している理由です。変数が null であるため、次のようになります。

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

一重括弧を使用しているため、bash はテスト条件として 1 つの単語しか認識しません。test コマンドが引数を 1 つしか認識しない場合、単語が空でない場合、結果は true になり、これらの各ケースで、単語に 2 文字が含まれます。

もちろん、修正は変数を宣言することです。また、bash の条件付き構造を使用する必要があります

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

二重括弧を使用すると、変数が空または null の場合でも、bash は条件に 2 つの単語を表示します。

于 2012-08-30T23:02:23.523 に答える
2

$file1変数を変更する$1か、スクリプトの先頭 (#!/bin/bash の後) に次を追加します。

set file1=$1

したがって、次のようにスクリプトを呼び出すことができます。

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

またはドル記号を削除するか、スクリプトを次のように置き換え$file1$1使用します./script.sh file1

于 2012-08-30T20:13:17.747 に答える