Question

I have tried countless ways to get what I want, but nothing seems to work. I always end up with something like 2:not found.

I want to capture the output of a command, and then test if it equals "!", like so:

function test() {
  local testv=$(command) 2>/dev/null
  if [ $(#testv) == "!" ]; then
    echo "Exclamation mark!"
  else
    echo "No exclamation mark."
  fi
}

How should I rewrite the code above to avoid the error test:2: = not found?

Was it helpful?

Solution

This should work:

if [ $testv = '!' ]; then

There were several problems here:

  • $(...) runs a command and substitutes its output; you want to substitute a variable value, so use $var or ${var}.
  • I have no idea what the # was doing there. ${#var} will get the length of $var, but that's not what you want here.
  • The test command (which [ is a synonym for) doesn't understand ==, so use = (if you're a C programmer that'll look wrong, but this is shell not C).
  • I don't think this is a problem in a script, but for interactive input "!" doesn't do what you expect. I used '!' to make sure the exclamation mark couldn't be interpreted as a history option.

Alternately, you could use [[ ]] instead of [ ], since it understands == (and has somewhat cleaner syntax in general):

if [[ $testv == '!' ]]; then

BTW, I'm trusting from the tag that this script is running in zsh; if not, the syntax will be a bit different (basic shells don't have [[ ]], and anything other than zsh will do unwanted parsing on the value of $testv unless it's in double-quotes). If you're not sure (or want it to be portable), here's a version that should work in any posix-compliant shell:

if [ "$testv" = '!' ]; then

OTHER TIPS

Try with this:

local testv=$(command 2>/dev/null)

since it's the output of the command you want to redirect.

(I have no idea what you mean by $(#testv) though.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top