简体   繁体   中英

Working with hidden files and files\folders that have spaces in the name

I have made a script that takes all of the files in the current directory, checks if it is a regular file or a folder and sets permissions to them.

My problem is when I encounter hidden files\\folders and files\\folders that have spaces in the name.

Here is my script:

#!/bin/bash
FILES=$(pwd)/*
for f in $FILES
  do
  if [ -f $f ]; then chmod u+x $f; fi
  if [ -d $f ]; then chmod u=w,g+r,o-rwx $f; fi
done

Here is an example of an error I get from the testing computer:

'test/.bwhajtbzmu xswxcgqsvz' has incorrect permissions: expected 250, got 414.

The other errors are basically the same.

I am not actually sure what is the problem here, if it is the fact that it is a hidden file or that it has a space in the name. I guess both things are the problem.

How can I modify the script so that it can work with hidden files and files that have space in the name ?

Thank you

PS. Please don't question the usefulness of the script, it is a school homework.

Handling whitespace in file names is tricky. First rule is: doublequotes around all usages of variables. Otherwise the shell interprets the spaces as separators. Unfortunately you cannot simply hold a list in a variable. You have to use array variables for this.

#!/bin/bash

FILES=( "$(pwd)"/* )

for f in "${FILES[@]}"
do
  if [ -f "$f" ]; then chmod u+x "$f"; fi
  if [ -d "$f" ]; then chmod u=w,g+r,o-rwx "$f"; fi
done

For handling hidden files and folders (the ones starting with a dot . ) you should best set the shell option dotglob which makes * also match these (which it otherwise doesn't). (Using .* is not good as it matches also . and .. which normally aren't wanted and things like .??* will not match stuff like .a which is normally wanted.):

shopt -s dotglob
FILES=( "$(pwd)"/* )
shopt -u dotglob

I would not recommend leaving it on, so I switch it off after using it.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM