简体   繁体   中英

Shell scripting - if statement difference

This a question of an exercise: What is the difference between the two "if" instructions?

#!/bin/bash
rm tmp
echo -n > tmp
for f in $*
do
        if test ! -f $f
        then
                echo $f does not exist as a file
                continue
        fi
        rm $f

        if [ ! -f $f ]
        then
                echo $f has been deleted successfully
        fi
        ls $f >> tmp
done
x='cat tmp | grep -c ^.*$'
echo result: $x

The square brackets are a synonym for the test command, instead of if test ! -f $f if test ! -f $f we can use if [ ! -f $f ] if [ ! -f $f ] .
Note: test is a command which takes expression and test or evaluates.

No difference. test and [ are builtins in most (all?; definitely in dash, bash, yash, ksh, zsh, fish) shells now:

$ type [ 
[ is a shell builtin
$ type test
test is a shell builtin

There's also executable versions of them:

$ which [
/usr/bin/[
$ which test
/usr/bin/test

Unlike cd , test (or [ ) doesn't need to be a builtin (at least not for the common options -- some shells' extensions require it to be a builtin), but the fork+exec overhead of an external executable is too much for the little things that test tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM