Boolean variable in a Shell Script

I'm writing a Linux Shell script and would like to have a Boolean variable called FileA_isPresent
I would like to set the variable to true if the file is present and false if not

Is this possible? I've used this in every other language I've used but looking on the net it seems that Linux shell scripts don't handle Boolean variables in the usual way?

Am I wrong? if so it would be great to get some pointers.
PJ0302917Asked:
Who is Participating?
 
simon3270Connect With a Mentor Commented:
Shell variables contain either numbers or strings, so you could store "true" and "false" in them, or 1 and 0.

You then test against the values as, for example, if $a is set to 0 (for false) or 1 (for true):
if [[ $a -eq 1 ]]; then
  # do something if $a is 1, for true
else
  # do something if $a is 0, for false
fi

Open in new window


text versions are more obvious, so
if [[ $a == "true" ]]; then
 # Action if true
else
  # action if false
fi

Open in new window

0
 
Murugesan NagarajanConnect With a Mentor Subject-matter expert at C++ C delivery, implementation, at UNIX oriented operating systems (Windows: CYGWIN_NT MINGW32_NT MINGW64_NT)Commented:
Not refreshed this page, before writing my comment. => to see comment from simon3270.

Yes it is possible.
Providing the comment base on:
>> I've used this in every other language
Sample ways:
/bin/ls -ld FileA_isPresent >/dev/null 2>&1
FileA_isPresentValidateUsingDollarQuestion=$?
echo $FileA_isPresentValidateUsingDollarQuestion used to be zero if that file is present or non zero if not present

Open in new window

Same using if (learn if elif -
if [[ -f ./FileA_isPresent ]]
then
     SaveRet=$?
     echo "FileA_isPresent file is present"
else
   SaveRet=$?
fi
echo SaveRet $SaveRet

Open in new window

Always better save $? using a variable.
$ /bin/ls -ld ./FileA_isPresent >/dev/null 2>&1
$ echo $?
2
$ echo $?
0
$# zero since previous echo $? worked.

Open in new window

You can view $? using:
export PS1='$LOGNAME@$HOSTNAME $PWD [ $? ]
$ '

Open in new window

0
 
arnoldConnect With a Mentor Commented:
You can test, as the example points, if the variable is defined it will be seen as try, or use true, 1

You need to provide a context to what it is you want the variable for.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.