0

I want to detect if the 1st bash input parameter is "debug"(string).

I write script like this:

#! /usr/bin/env bash

if [ "$#" -eq "1" && "$1" -eq "debug" ]; then
    echo "hello debug"
fi

Error message:

line 3: [: missing `]'

I don't know why, please help.

1
  • 2
    There's no real need to test $# here; you can ignore additional arguments if present, and if $# is 0, then "$1" = debug will be false since $1 expands to the empty string. Commented Jun 13, 2019 at 2:10

2 Answers 2

5

Compare strings with ==, -eq is an arithmetic operator. Also, within [] you have to use the -a operator instead of &&, or split it in two. Here are a few different ways to write the same thing:

if [[ $# -eq 1 && "$1" == "debug" ]] ; then
    echo "hello debug"
fi
if [[ "$#" == "1" && "$1" == "debug" ]] ; then
    echo "hello debug"
fi
if [ "$#" == "1" ] && [ "$1" == "debug" ] ; then
    echo "hello debug"
fi
if [ "$#" == "1" -a "$1" == "debug" ] ; then
    echo "hello debug"
fi
Sign up to request clarification or add additional context in comments.

1 Comment

Splitting in two is preferable; -a is non-standard and considered obsolete by POSIX.
2

Instead of [ "$#" -eq "1" && "$1" -eq "debug" ], use either [ "$#" -eq "1" ] && [ "$1" -eq "debug" ] (recommended; see https://www.shellcheck.net/wiki/SC2166) or [ "$#" -eq "1" -a "$1" -eq "debug" ]. The problem is that && is bash's way of saying "and", rather than -a, which is test's way of saying "and". You can't use a bash "and" inside of test.

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.