Skip to content
Advertisement

How do I escape spaces in file paths when iterating in a for loop with a shell script in Linux?

I am writing a shell script in Linux that takes a file path and iterates over all files in the path. When a file is found it performs some logic. If a folder is found the function calls itself passing the folder as an argument. It works well unless there is white space in the folder path.

# I have tried the following with no success:
#   for f in "$ROOT_FOLDER_PATH" do
#   for f in "${ROOT_FOLDER_PATH}" do
#   for [f in "$ROOT_FOLDER_PATH"] do
#   for [[f in "$ROOT_FOLDER_PATH"]] do


# Most of the logic was removed to give a bare minimum example.
function extension_fixer(){
  ROOT_FOLDER_PATH="${1}"
  echo "ROOT FOLDER PATH: $ROOT_FOLDER_PATH/*"
  for f in $ROOT_FOLDER_PATH/*; do
    echo "FOLDER: $f"
    if [[ -d "$f" ]]; then
      # If the file is a folder, recursively call the extension_fixer function on that folder.
      extension_fixer "${f}"
    elif [[ -f "$f" ]]; then
      echo "Do something..."
    else
      echo "$f is not valid"
      exit 1
    fi
  done
}

extension_fixer "/home/www/accounts/210"

Advertisement

Answer

Double quotes missing in

for f in "$ROOT_FOLDER_PATH"/*; do
#        ~                 ~
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement