Reputation: 31
I am looping through a directory and need to find all files that are not executable. I know
if [ -x $dir ]; then
echo "$dir is an executable file"
fi
shows that it is executable but how do I do the opposite of this? I have tried
if [ !-x $dir ]; then
echo "$dir is not-executable"
fi
however that does not work.
Upvotes: 3
Views: 2302
Reputation: 212248
Either:
if ! [ -x "$dir" ]; then
echo "$dir is not an executable file"
fi
or:
if [ ! -x "$dir" ]; then
echo "$dir is not an executable file"
fi
will work. In general, any command can be negated by !
. So if cmd
returns non-zero, ! cmd
returns zero. The [
command also accepts !
as an argument, so that [ expression ]
is inverted with [ ! expression ]
. Which you choose is pretty much a stylistic choice and makes little difference.
Of course, you can also just do:
if [ -x "$dir" ]; then
:
else
echo "$dir is not an executable file"
fi
Upvotes: 4
Reputation: 361605
Running the line through Shell Check shows:
if [ !-x $dir ]; then
^-- SC1035: You are missing a required space here.
^-- SC2086: Double quote to prevent globbing and word splitting.
Adding the missing space and quotes results in:
if [ ! -x "$dir" ]; then
You can also put the !
outside the brackets using the generic syntax if ! command
, which works on any command:
if ! [ -x "$dir" ]; then
Upvotes: 4