3

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.

1
  • 1
    Spacing is crucial in shell scripts. There's a vast difference between [ !-x $dir ] and [ ! -x $dir ] (and you should use [ ! -x "$dir" ] to avoid some surprises). Commented Mar 9, 2021 at 20:30

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

4

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.