转义的文件名斜杠

aki*_*iva 0 string bash escaping

我想从用户输入的字符串生成文件名,并确保它安全地转义.

例如,如果用户输入/usr/bash输出将是\/usr\/bash ,如果输入是The great theater输出The\ great\ theater.

Joh*_*ica 5

你确定需要这样做吗?这是一种代码味道.除了改变你的输入之外,你很可能有更好的方法去做你想做的事情.在使用变量时正确引用变量通常就足够了:

$ file='some file name.txt'
$ touch "$file"
$ ls "$file"
some file name.txt
Run Code Online (Sandbox Code Playgroud)

但是,如果您坚持使用%qprintf 的格式:

$ str='The great theater'
$ printf '%q\n' "$str"
The\ great\ theater
$ escaped=$(printf '%q' "$str")
$ echo "$escaped"
The\ great\ theater
Run Code Online (Sandbox Code Playgroud)

请注意,这不会转义斜杠,因为它们通常不是特殊字符.