LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   why does if [ ${var:0:2}='AA' ] always return true (https://www.linuxquestions.org/questions/programming-9/why-does-if-%5B-%24%7Bvar-0-2%7D%3Daa-%5D-always-return-true-130328/)

blish_blash 12-31-2003 08:21 AM

why does if [ ${var:0:2}='AA' ] always return true
 
Hi and happy new year !
can someone tell me why does

if [ ${var:0:2}='AA' ]

always return true, and tell me how to change if to test the first two characters in variable var ?

Greetings,
Ron

Hko 12-31-2003 08:51 AM

Happy new year to you too.

That happens because you need to have spaces around the '='.
It's also better (at least in this case) to have double quotes around ${var:0:2}. Without the double quotes you'll get an error if "var" happens to be emtpy.

So, this works:
Code:

#!/bin/bash

var=$1

if [ "${var:0:2}" = "AA" ] ; then
    echo True
fi



All times are GMT -5. The time now is 01:19 PM.