I am writing a script which takes a directory name from user, then find files inside it. The script may fail if the user use some special characters with their directory name.
$ var="-foobar";
$ find "$var";
find: unknown predicate `-foobar'
For a lot of commands, it is easy to avoid the problem by giving -- to indicate that it is an end of options. But it does not with with find:
$ find -- "$var";
find: unknown predicate `-foobar'
What should I do to handle directory with unpredictable characters?
-foobar) or absolute (/tmp/-foobar), just preceeding it with./is not safe. I guess the solution to handle this would be:find $(realpath -- "$var").Thanks for your suggestion.
– Livy Sep 03 '19 at 04:08--does work to indicate the end of options. Comparefind -L .andfind -- -L .POSIX defines-Hand-Las options, nothing more. Implementations may add few options, but still paths and expression are not options. – Kamil Maciorowski Sep 03 '19 at 04:09realpathwon't help if you want relative paths to stay relative. I mean you may wantfindto print/use-foobar/bazor./-foobar/baz, not/home/livy/-foobar/baz. I can imagine scenarios where this matters. Considerfind "$(printf '%s\n' "$var" | sed '1 s|^-|./-|')". – Kamil Maciorowski Sep 03 '19 at 06:07sedcommand and don't understand it. – Livy Sep 03 '19 at 06:48tarwithout full paths (this). Aboutsed:sed '1 s|^-|./-|'will replace-at the very beginning of the first line with./-. Input without leading-is unaffected. The "first line" condition may seem excessive but note a name like-a\n-b(where\ndenotes the newline character) is a valid name in general. You don't want to alter the second line. – Kamil Maciorowski Sep 03 '19 at 07:38