Nick Nick - 2 months ago 10
Linux Question

How to read spaces in FOR loop

I'm new here. I am trying to write a de-bloat script for Android.
Below is my code :-

#/system/bin/sh
clear
list=$(cat <<'EOF'
Beauty\ Plus
blackmart
Cam\ Scanner
Tencent
EOF
)

for f in $(echo "$list");
do
if [ -e /sdcard/$f* ];
then
rm -rf /sdcard/$f*
echo -e "Deleted /sdcard/$f*."
else
echo -e "/sdcard/$f* not found."
fi
done


Now here is the issue, it reads both the occurrences with space as different entries. I have made sure that I use echo with variables enclosed in quotes.

If I just try

echo "$list"


Then, it gives the desired output. I have also tried using the

echo "$list" | while read f
do
echo $f
done


But, it also gives the same output.
Please help me with this.
The output should be like this :-

Beauty\ Circle
Cam\ Scanner


so that I write my further code as :-

for f in $(echo "list");
do
rm -rf /sdcard/$f
echo -e "Removed \/sdcard\/$f"
done


Thank you.

P.S: I don't want to use

rm -rf /sdcard/$f*

Answer

If you really need to run the script with /bin/sh (which might be a shell that does not support arrays), you need to use a while loop instead of a for loop:

while IFS= read -r f; do
  rm -rf /sdcard/"$f"
  printf 'Removed /sdcard/%s\n' "$f"
done <<EOF
Beauty Plus
blackmart
Cam Scanner
Tencent
EOF 

If you can use #!/bin/bash, then you can use a for loop to iterate over an array instead of a regular parameter.

list=( "Beauty Plus"
blackmart
"Cam Scanner"
Tencent
)
for f in "${list[@]}"; do
  rm -rf /sdcard/"$f"
  printf 'Removed /sdcard/%s\n' "$f"
done