Problem with BASH conditionals - passing condition as variable
I'm trying to implement an assert function similar to:
http://www.codelibary.com/Bash/Assert.html However, I'm having trouble with file existence testing when the file name has a space in it. I have distilled the problem down to the following: This code works as expected, printing 'yes' if '~/test file' exists, and no if not. Code:
[ -e "~/test file" ] && echo yes || echo no Code:
condition=' -e "~/test file" ' Code:
bash: [: "~/test: binary operator expected Note that if you simply use a file path without a space, both cases work perfectly. Is this a BASH bug possibly? I just can't understand why the first would work, but the second wouldn't. |
Quote:
Code:
filepath="~/test file" |
I understand you want to test conditional expressions contained in a variable. Intriguing idea! :)
It will require a detailed understanding of how the shell works. For eaxmple: Code:
c@CW8:~/d/bin/try$ /bin/ls ~/'test file' Knowing the order of shell operations will be essential when designing a solution. That's all I have time for right now. I'm posting it in case you are in a hurry. Back later. QUICK EDIT: the solution will almost certainly require the eval built-in command. |
Quote:
Code:
c@CW8:~/d/bin/try$ [ -e "~/test file" ] && echo yes || echo no |
Thanks for the replies everyone. I think I figured it out.
catkin: I made a bad assumption that the ~/ would be expanded. I actually used the following tests: Code:
smaddox@smaddox-desktop:~$ touch "test file" If anyone wants to see it in action, here is a testing script: Code:
#!/bin/bash Code:
$ ./test |
Thanks for posting your solution. I was quite looking forward to trying to implement it without creating a sub-process (for performance reasons) but there seems little point now you have a working (and tidily programmed :)) solution there doesn't seem much point.
|
6 simple examples that worked for me even with sh or dash:
Code:
#/bin/sh |
Quote:
If the filename variable's value begins with ~/ then I think eval is required. |
catkin: If you are worried about performance, you could always add a DEBUG var, and check for it at the beginning of the script.
Code:
if [ DEBUG -ne 0 ]; then |
All times are GMT -5. The time now is 02:21 AM. |