开发者

Bash - if and for statements

I am little unfamiliar with the 'if...then...fi' and the 'for' statements syntax.

Could anyone explain what the "$2/$fn" and "/etc/*release" in the code snippets below mean?...specifically on the use of the forward slash....and the asterisk...

if [ -f "$filename" ]; then
    if [ ! -f "$2/$fn" ]; then
        echo "$fn is missing from $2"
        missing=$((missing + 1))
    fi
fi

and

function system_info
{


if ls /etc/*release 1>/dev/null 2>&1; then
    echo "<h2>System release info</h开发者_Python百科2>"
    echo "<pre>"
    for i in /etc/*release; do

        # Since we can't be sure of the
        # length of the file, only
        # display the first line.

        head -n 1 $i
    done
    uname -orp
    echo "</pre>"
fi

}   # end of system_info

...thx for the help...


/etc/*release : here the * will match any number of any characters, so any thing /etc/0release , /etc/asdfasdfr_release etc will be matched. Simply stated, it defined all the files in the /etc/ directory which ends with the string release.

The $2 is the 2nd commandline argument to the shell script, and $fn is some other shell variable. The "$2/$fn" after the variable substitutions will make a string, and the [ -f "$2/$fn" ] will test if the string formed after the substitution forms a path to a regular file which is specified by the -f switch. If it is a regular file then the body of if is executed.

In the for loop the loop will loop for all the files ending with the string release in the directory /etc (the path). At each iteration i will contain the next such file name, and for each iteration the first 1 line of the file is displayed with the head command by getting the file name from variable i within the body.

It is better to check the manual man bash and for if condition check man test . Here is a good resource: http://tldp.org/LDP/Bash-Beginners-Guide/html/


The forward slash is the path separator, and the * is a file glob character. $2/$fn is a path where $2 specifies the directory and $fn is the filename. /etc/*release expands to the space separated list of all the files in /etc whose name ends in "release"


Dollar sign marks variable. The "-f" operator means "file exsists".

So,

[ -f "$filename" ]

checks if there is file named the same as value contained in $filename variable.

Simmilar, if we assume that $2 = "some_folder", and $fn = "some_file", expression

[ ! -f "$2/$fn" ]

returns true if file some_folder/some_file doesn't exsist.

Now, about asterisk - it marks "zero or more of any character(s)". So, expression:

for i in /etc/*release; do

will iterate trough all folders named by that pattern, for example: /etc/release, /etc/666release, /etc/wtf_release...

I hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜