Phillip T. Phillip T. - 1 month ago 6
Bash Question

Shell Scripting: Convert file string to be usable in a command

I'm stuck on figuring out a way to take text of a file name and converting it into a string that can be usable in commands.

I would like to take a file name (for example:

[foo] bar - foo.mkv
) and add backslashes to spaces, square brackets, and any other characters (for example
\[foo\]\ bar\ -\ foo.mkv
) so that they are usable in a command such as
mv
.

Thank you for helping me.

Answer

I don't think there is a need for that. You could enclose the filename variable in double quotes and the commands would handle the rest.

$ touch "[foo] bar - foo.mkv"
$ ls
[foo] bar - foo.mkv
$ mv "[foo] bar - foo.mkv" "abcd"
$ ls
abcd

So just enclose the string in double quotes and it must solve your problem:

mv "$oldname" "$newname"

There's rarely a need, but if you want to have substitutions you can use this:

$ printf '%q' "[foo] bar - foo.mkv"
\[foo\]\ bar\ -\ foo.mkv