0

I am trying to use variables to direct program output to different locations based on some user config settings.

if [ -f "vars/debug.var" ]; then
   DUMP=''
else
   DUMP='&> logs/dump.log'
fi

...

ping -I eth0 -c 10 www.google.com $DUMP

...

So, if the file debug.var exists, DUMP is an empty string, but if it does not exist I want to pipe the output to the dump.log file.

I have tried a lot of different combinations of the variable and command and nothing has worked out... I keep getting the error

ping: unknown host &>

Anybody have an idea? Or is it just not possible?

3 Answers 3

2
eval "ping -I eth0 -c 10 www.google.com $DUMP"
Sign up to request clarification or add additional context in comments.

9 Comments

Huh? Now what if it has a space in its filename?
@Aleks-DanielJakimenko, it works when DUMP='>& logs/my\ dump.log'.
Hah, it's like not quoting your variables and blaming the user that it was his fault when he entered an asterisk in path. I'd better play on safe side.
So, where is the list of expressions that people should avoid when using your solution? For example, you have to escape ;, ', ", $, < and many others...
@Aleks-DanielJakimenko, you are creating a problem where none exist. The OP's question was pretty simple, with none of the complexities you are trying to account for. Every solution does not have to be fool proof. We should find solutions that are no complex than they need to be.
|
1

Instead of messing around with eval (which is a security hole)

if [ -f "vars/debug.var" ]; then
   : # nothing
else
   exec &> logs/dump.log
fi
ping -I eth0 -c 10 www.google.com

What exec does is allowing you to redirect output as needed, and you can do that in a sub-shell (...) as well to limit the scope of the re-direct.

2 Comments

+1, However, originally I thought that the point was to be able to change '&>' to something else via variable. Also, what if you want to log some commands but at the same time you want some other commands to print straight into stdout?
I like how clean this is, unfortunately there is other output that I need over stdout. This pipes all of my output to the dump file.
0

Here is another safer variant that allows you to have arbitrary paths.

DU='&>'
MP='logs/ * /du mp.log'
eval "xargs ping -I eth0 -c 3 www.google.com $DU \"\$MP\""

Or you can use an array:

DUMP=('&>' 'logs/ * /du mp.log')
eval "xargs ping -I eth0 -c 3 www.google.com $DUMP \"\${DUMP[1]}\""

And you can quote it like this to save 1 character

eval "xargs ping -I eth0 -c 3 www.google.com $DUMP "'"${DUMP[1]}"'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.