问题
I am trying to build a condition that check if file has execute access bit set. I can't use grep and find.
I tried something with checking the "x" letter in the ls -l
command but this is wrong in many cases.
for val in `ls $1`
do
if [[ "`ls -l $1/$val`" -eq *w* ]]
then
rm $1/$val
fi
done
Please help or give some advices!
回答1:
There is no need to parse the output of ls
to see if a file is executable. Shell provides the built-in -x
check for that. Using -x
feature, your loop could be re-written as:
for file in "$1"/*; do
[[ -x "$file" ]] && rm -- "$file"
done
See also:
- How do I tell if a regular file does not exist in Bash?
As Charles suggested - Why you shouldn't parse the output of ls(1)
BashFAQ/087 - How can I get a file's permissions (or other metadata) without parsing ls -l output
回答2:
if [ -x "$file" ]; then
# do something
fi
You can get many more options of file testing using man
:
~]# man test
....
-x FILE
FILE exists and execute (or search) permission is granted
Following should work:
~]# find $1 -type f | while IFS='' read -r -d '' p;
do
if [ -x "$p" ]; then
echo "removing $p";
rm "$p";
fi;
done
find
command gets all the files (including .
) in the directory given by $1
. while
reads each of these output, if then
checks individual files for executable permission with-x
.
EDIT
After some comments, here is a swifter example:
find "$1" -type f -executable -exec rm -- {} \;
来源:https://stackoverflow.com/questions/42633413/how-to-check-if-a-file-is-executable-in-bash