When you iterate paths and do something with them, you might be tempted write this:
This command looks fine, but has two problems:
find . -name blah | xargs rm -fyeah, I know there is a switch
-exec
in find
, I just don't like it.This command looks fine, but has two problems:
- The length of arguments maybe exceeds the limit of the shell.
- The file path may contains some special characters, such like quotes, spaces.
To solve the first issue, a loop maybe useful:
You can change the delimiter temporary as a workaround, but this will impacts all actions in the loop, I personally don't recommend this.
for path in `find . -name blah` ; do rm -f "path" doneThis solves the first issue, but the second one remains. For loop treats spaces and newlines as delimiters. But if paths contain spaces, they will cause error.
You can change the delimiter temporary as a workaround, but this will impacts all actions in the loop, I personally don't recommend this.
Or we can use a while loop:
find . -name blah | while read path ; do rm -f "$path" doneshould be just fine.
Another common error , comes from:
Good practice is:
if [ $str = blah ] ; thenThe problem is,
$str
maybe unset or a null string, or worse, injected with a string such like -f
.Good practice is:
if [ x"$str" = xblah ] ; then
沒有留言:
張貼留言