Created
June 4, 2018 16:54
-
-
Save haolian9/a3c569489f9cc1ab7af721874770e9be to your computer and use it in GitHub Desktop.
escape filename using shell script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
# todo | |
# follow convention | |
# * echo -n | awk '{ print $0 }' | |
# * echo | awk '{ print $0 }' | |
read_escape() { | |
while read -r filename; do | |
escape $filename | |
done | |
} | |
escape() { | |
local raw="${*:?requires string which needs to be escaped}" | |
local blacklist=( | |
# -option; mv | |
'^-' | |
# php.quotemeta() | |
'\.' '+' '\\' '*' '?' '\[' '\]' '\^' '(' ')' '\$' | |
# filename | |
' ' | |
) | |
local pattern="${blacklist[0]}" | |
for (( i=1; i < ${#blacklist[@]}; i ++ )) { | |
pattern="$pattern\\|${blacklist[$i]}" | |
} | |
echo $raw | sed "s#\($pattern\)#\\\&#g" | |
} | |
test_escape() { | |
local input='-a-b.a\c+d*e?f[g]h^i(j)k$l m' | |
local expect='\-a-b\.a\\c\+d\*e\?f\[g\]h\^i\(j\)k\$l\ m' | |
[ "$(escape $input)" != "$expect" ] && { | |
>&2 echo "[x] escape did not work as expected." | |
return 1 | |
} | |
echo "everything is fine." | |
} | |
case "$1" in | |
"escape") | |
shift | |
escape "$@" | |
;; | |
"test") | |
test_escape | |
;; | |
"read") | |
read_escape | |
;; | |
"") # maybe this script be sourced | |
;; | |
*) | |
echo "unsupport operation" | |
exit 1 | |
;; | |
esac | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment