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.
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
if ! command
, which works on any command:
if ! [ -x "$dir" ]; then
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
! cmd
returns zero. The [
command also accepts !
as an argument, so that [ expression ]
is inverted with [ ! expression ]
[ ! 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
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.