Home > database >  bash operators in if-statement
bash operators in if-statement

Time:07-22

Im new to bash and can't understand how the operator quite work here. The goal is to creating a script which ask user to input "y" to run the command or "n" to not run.

by using ==:

All inputs get passed such as (y, n, a, abc, etc..)

if (($TFENGINE_VAR==y))

by using =:

All inputs get rejected such as (y, n, a, abc, etc..)

if (($TFENGINE_VAR=y))

echo "run tfengine? (y/n)"
read TFENGINE_VAR
if (($TFENGINE_VAR==y))
then
  echo "running tfengine command.."
  sleep 1
  tfengine --config_path=main.hcl --output_path=terraform/ -delete_unmanaged_files
else
  echo "continue.."
  continue
fi

CodePudding user response:

Expressions surrounded with (( )) are evaluated as numeric expressions.

You need to use the test command, which returns 0 if test is successful, and a number different from 0 if not.

There are several options to the test command. In your case, you want to compare strings, so use each parameter surrounded with double quotes.

Also, when comparing strings you don't use == as the comparison operator.

if test "$TFENGINE_VAR" = "y"
then
   ...

Take a look at test man page: http://man.he.net/?topic=test&section=all

CodePudding user response:

Your question is:

how the operator quite work here

The ((...)) is an arithmetic expression. Inside, all strings are interpreted as variables, and undefined variables are interpreted as equal 0. The exit status of ((...)) is non-zero if the expression is equal to zero, and the exit status is zero if the expression inside is equal to non-zero.

Because y variable is not defined, y is equal to 0. The (( $TFENGINE_VAR == y )) does the same as (( $TFENGINE_VAR == 0 )).

If you want to compare strings, you would use [[ or [ or test command.

All inputs get rejected such as

Sure, = is assignment inside arithmetic expression. If you input abc, then (( $TFENGINE_VAR = y )) becomes (( abc = 0 )) and it assigns the value 0 to variable abc. Note that variable expansion happens before the expansion of variables inside ((.

$ TFENGINE_VAR=abc
$ (($TFENGINE_VAR=y))
$ echo $abc
0
$ y=12345
$ (($TFENGINE_VAR=y))
$ echo $abc
12345

The result of assignment is equal to the value assigned, 0 in this case, so ((...)) exits with non-zero exit status, failure, so if branches to else part.

  • Related