首页 > 解决方案 > How to detox BASH input or variable?

问题描述

I am currently using (tr -d ' ' <<< "$LOC1")to detox (change spaces into \ / etc.) the file path. This does not work very well though since it only removes spaces instead of correctly formatting like "File\ path/". Since the variable $LOC1 can contail different paths it needs to be "adaptable".

I could not find any solutions that allowed this with a "flexible" file path / variable. So I'm humbly asking here.

I started learning how to "script?" yesterday so excuse me if I couldn't make myself clear.

 #!/bin/bash

LOC1=$(zenity --file-selection --directory --title="Select first directory")

LOC2=$(zenity --file-selection --directory --title="Select second direcotry")
LOC1=$(tr -d ' ' <<< "$LOC1")
LOC2=$(tr -d ' ' <<< "$LOC2")
clear
rsync -r --info=progress2 --delete-excluded $LOC1 $LOC2
read -n 1 -s -r -p "Your back-up is complete, Press any key to exit..."

Thanks in advance!

edit: The problem was that zenity gives user input to select a directory but doesn't remove the spaces in the path to that directory. it will output for example: /media/productivity/Seagate backup A/Back-up instead of /media/productivity/Seagate\ backup\ A/Back-up

How do I make it so the script detoxes the file path without knowing how many white spaces there are going to be?

标签: linuxbashshellscripting

解决方案


AFAIK, you don't need to do this path modifications for the script you are running. Just quote all the variables so they can be interpreted properly:

#!/bin/bash

LOC1=$(zenity --file-selection --directory --title="Select first directory")
LOC2=$(zenity --file-selection --directory --title="Select second direcotry")

clear
rsync -r --info=progress2 --delete-excluded "$LOC1" "$LOC2"
read -n 1 -s -r -p "Your back-up is complete, Press any key to exit..."

推荐阅读