简体   繁体   中英

Handle Whitespace and special character in shell script (using gio)

Hy,

I am trying to handle white spaces and special characters like "&" in a shell script which is supposed to set custom directory icons using gio in Ubuntu 18.04.

When directory names consist only of a single word eg. MyFolder the following script works just fine:

for dir in $(find "$PWD" -type d); do
icon="/.FolderIcon.png"
iconLocation="$dir$icon"
if [ -a "$iconLocation" ]; then
front="file://"
gio set "$dir" metadata::custom-icon "$front$iconLocation"
fi
done

However when the directory is named eg. "A & B" the above script does not change the icon of the respective directory.

So my question is: Is there a way to handle directories named like "A & B" in my script?

First, for var in $(cmd) is generally an antipattern.

In most cases, what you'd probably want is something like suggested in https://mywiki.wooledge.org/BashFAQ/020 -

while IFS= read -r -d '' dir; do 
  # stuff ...
done < <(find "$PWD" -type d -print0)

But for this particular example, you might just use shopt -s globstar .
I made a directory with an A & B subdirectory and ran this test loop:

$: shopt -s globstar
$: for d in **/; do touch "$d.FolderIcon.png"; if [[ -e "$d.FolderIcon.png" ]]; then ls -l "$d.FolderIcon.png"; fi; done
-rw-r--r-- 1 paul 1234567 0 Apr 20 09:25 'A & B/.FolderIcon.png'

**/ has some shortcomings - it won't find hidden directories, for example, or anything beneath them. It is pretty metacharacter-safe as long as you quote your variables, though.

Thanks to the answer of Paul Hodges the following solution finally worked for me:

shopt -s globstar
location="/path/to/location/you/want/to/modify"
prefix="file://"
for d in **/; do  
if [[ -e "$d.FolderIcon.png" ]]; 
then gio set "$d" metadata::custom-icon "$prefix$location/$d.FolderIcon.png"; 
fi; 
done

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