Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to read a string variable and compare it with string constant in bash

I need to read a string variable and to check if it’s equal to string ‘qwe’.
I try this code:

read VAR1
if ["$VAR1" == "rwx"]; then
    current=$current+1
fi

but terminal says

[rwx : command not found

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

[ is a command, not just syntax. Commands need to be separated from their arguments with whitespace:

if [ "$VAR1" = "rwx" ]; then ...
#   ^               ^

See help if at an interactive prompt:

$ help if
if: if COMMANDS; then COMMANDS; [ elif COMMANDS; then COMMANDS; ]... [ else COMMANDS; ] fi
    Execute commands based on conditional.

    The `if COMMANDS' list is executed.  If its exit status is zero, then the
    `then COMMANDS' list is executed...

There’s nothing in there about [...], what comes after if is a command list, and the exit status determines the "success" of the conditional.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading