title: Assigning the result of 'test' to a variable
body: <p>I'm writing a script where I need to use the output of a file test in several places, including inside a shell function. I would like to assign the file existence to a shell variable, like this: <code>file_exists=[ -f $myfile ]</code>.</p>
  
  <p>Just to make sure that I've got my bases covered, I start by touching a file, and testing its existance: </p>
  
  <pre><code>file='a'
  touch $file
  if [ -f $file ]
  then
      echo "1 -- '$file' exists"
  fi
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>1 -- 'a' exists
  </code></pre>
  
  <p>The file was created successfully -- no surprises, but at least I know that I'm not dealing with any permissions issues or anything.</p>
  
  <p>Next I test to make sure that I can store a boolean expression in a variable:</p>
  
  <pre><code>mytest=/bin/true
  
  if $mytest
  then
      echo "2 -- \$mytest is true"
  fi
  </code></pre>
  
  <p>Output:</p>
  
  <pre><code>2 -- $mytest is true
  </code></pre>
  
  <p>So I've got the basics covered -- conditional expressions should emit the same output as <code>/bin/true</code> or <code>/bin/false</code>... but that's not what I'm seeing:</p>
  
  <pre><code>mytest=[ -f $file ]
  if $mytest
  then
      echo "3 -- \$mytest is true [expect true]"
  else
      echo "3 -- \$mytest is false [expect true]"
  fi
  </code></pre>
  
  <p>This fails with the following error:</p>
  
  <pre><code>-f: command not found
  </code></pre>
  
  <p>I get the same error message if i use <code>test -f $file</code> rather than <code>[ -f $file ]</code>.</p>
  
  <p>If I put a space in front of the <code>[</code>, the error goes away...</p>
  
  <pre><code>mytest= [ -f $file ]
  if $mytest
  then
      echo "4 -- \$mytest is true [expect true]"
  else
      echo "4 -- \$mytest is false [expect true]"
  fi
  </code></pre>
  
  <p>The output appears to be correct:</p>
  
  <pre><code>4 -- $mytest is true [expect true]
  </code></pre>
  
  <p>... but if I remove the file, I should get the opposite result:</p>
  
  <pre><code>rm $file
  mytest= [ -f $file ]
  if $mytest
  then
      echo "5 -- \$mytest is true [expect false]"
  else
      echo "5 -- \$mytest is false [expect false]"
  fi
  </code></pre>
  
  <p>... and I don't:</p>
  
  <pre><code>5 -- $mytest is true [expect false]
  </code></pre>
  
  <p>To be fair, I expected the space to mess with the truth value:</p>
  
  <pre><code>mytest= /bin/false
  if $mytest
  then
      echo "6 -- \$mytest is true [expect false]"
  else
      echo "6 -- \$mytest is false [expect false]"
  fi
  </code></pre>
  
  <p>Outputs:</p>
  
  <pre><code>6 -- $mytest is true [expect false]
  </code></pre>
  
  <p>So, how do I store the output from the <code>test</code> builtin in a shell variable?</p>