How do I suppress stderr warning messages from a command inside command substitution?
Solution 1
Some expansions happen before redirection so you have to place it directly against your tr
command:
touch ~/deleted/$(echo "directory_"$(readlink -f foo)|tr '/' '\' 2> /dev/null)
Solution 2
The error message means that you have an unescaped backslash. In the *nix world, special characters are 'escaped' by adding a backslash before them. That means that they're interpreted as simple characters and not special ones. For example:
$ printf 'foo\nbar'
foo
bar
The \n
is a special character that means newline. But if we escape the slash we get:
$ printf 'foo\\nbar'
foo\nbar
So, you can get rid of it either by escaping the backslash:
touch ~/deleted/"$(echo "directory_$(readlink -f -- "$1")"|tr '/' '\\')
Or by redirecting the error output of tr
(not of touch
which is what you were doing):
touch ~/deleted/"$(echo "directory_$(readlink -f -- "$1")"|tr '/' '\' 2> /dev/null)
However, I cannot stress enough that it is a Very Bad Idea® to create file names with backslashes. Really. They will be hell to parse and deal with later on. Why not use another character?
Solution 3
Use single quotes with double back slash, and you will not get any error.
touch ~/deleted/$(echo "directory_"$(readlink -f foo)|tr '/' '\\')
Related videos on Youtube
lonewarrior556
Updated on September 18, 2022Comments
-
lonewarrior556 almost 2 years
touch ~/deleted/$(echo "directory_"$(readlink -f foo)|tr '/' '\') 2> /dev/null
where foo is a directory
It's reading the full pathname of foo and creating it as a file replacing all '/' with '\' and putting a directory_ in front so the directory
/home/test/foo
would create a filedirectory_\home\test\foo
It does exactly what I want except a warning keeps printing
tr: warning: an unescaped backslash at end of string is not portable
a. I don't know what that means b. I would like it to not show
I tried to redirect stderr to
/dev/null
but it doesn't work. How do I suppress it?-
Admin almost 10 yearsIt's in a script. to run it I "sh script nameOfDirectory"
-
Admin almost 10 yearsPlease edit your question to clarify accordingly. I also strongly suggest you consider using any other character but
\
, backslashes are special as you're finding out.
-
-
cuonglm almost 10 yearsMaybe the OP from windows environment?
-
terdon almost 10 years@Gnouc yes, which means it's an even worse idea to use `\`.
-
ThomasH over 5 yearsFun thing is, if
url=D:\Programs\Git\mingw64/share/doc/git-doc/git-log.html
then ``url1=echo $url | tr '\\\ '/'``` shows the warning, while
url1=$(echo $url | tr '\\' '/')` does not. -
fbiville over 5 yearsGit Bash in Windows 10 complains about
[...] | tr '\\' '/'
although the backslash is properly escaped. Go figure. -
terdon over 5 years@Rolf Windows uses `` as the path delimiter, so that might cause issues there.