esbej
esbej

Reputation: 27

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

Upvotes: 0

Views: 165

Answers (2)

Petr Skocik
Petr Skocik

Reputation: 60068

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.

Upvotes: 1

Shibin Raju Mathew
Shibin Raju Mathew

Reputation: 930

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

Upvotes: 3

Related Questions