Reputation: 35
If I execute this command directly from CLI, I don't have any problem:
~ # apt autoremove 1>$- 2>$-
~ #
But if I call it from a script I have some errors: Here is the script:
#!/bin/bash -x
NOVERBOSE='1>$- 2>$-'
apt autoremove $(echo ${NOVERBOSE})
And here is the output:
~ # /bin/bash -x test2.sh
+ NOVERBOSE='1>$- 2>$-'
++ echo '1>$-' '2>$-'
+ apt autoremove '1>$-' '2>$-'
Reading package lists ... Done
Building the dependency tree
Reading status information ... Done
E: Unable to find package 1> $
E: Unable to find a package matching the regular expression "1> $"
E: Unable to find package 2> $
E: Unable to find a package matching the regular expression "2> $"
I don't understand why echo add some singles quotes around each part of the variable.
Upvotes: 1
Views: 92
Reputation: 530920
NOVERBOSE
should be a flag that indicates the desire to suppress output, not the syntax to do so. You then test the value and redirect output (or not) as appropriate.
if [[ $NOVERBOSE = [Yy]* ]]; then # e.g., y, Y, yes, Yes, etc
apt autoremove > /dev/null 2> /dev/null
else
apt autoremove
fi
If you don't like running apt
"twice" like this, you can redirect to /dev/stdout
and /dev/stderr
explicitly as a no-op redirection.
if [[ $NOVERBOSE = [Yy]* ]]; then
out=/dev/null
err=/dev/null
else
out=/dev/stdout
err=/dev/stderr
fi
apt autoremove > "$out" 2> "$err"
Upvotes: 4
Reputation: 780724
echo
isn't adding quotes, that's just how the -x
option shows where each argument begins and ends.
The problem is that I/O redirections are not processed after expanding variables. You need to use eval
to re-parse the line.
eval "apt autoremove $NOVERBOSE"
Upvotes: 2