-1

I have this bash script getting a Boolean parameter, based on the answer here
I created this simple condition, for some reason I am getting false results

#!/bin/bash

copyFile() {
    echo "copyFile #Parameter:$1"

    if [ "$1" ]; then
             echo "Parameter is true"
        else
             echo "Parameter is false"
        fi
}



copyFile true
copyFile false

execution result:

[admin@local_ip_tmp]$ ./test.sh
copyFile #Parameter:true
Parameter is true
copyFile #Parameter:false
Parameter is true

The last result should have "Parameter is false" I am not sure what is going on.
What am doing wrong?

7
  • 4
    Hint: false is just a string and it is not empty
    – anubhava
    Commented May 24, 2021 at 20:04
  • 2
    Test what you want to test accurately. Your current test is equivalent to if [ -n "$1" ] (if $1 is not empty). What are you after? if [ "$1" = "true" ] or if [ "$1" != "true" ] or if [ "$1" = "false" ] or … Commented May 24, 2021 at 20:10
  • 1
    Remove [ and ].
    – Cyrus
    Commented May 24, 2021 at 20:13
  • 1
    @JavaSheriff, personally, I recommend using arithmetic test contexts with integer constants. if (( $1 )); then ... will treat 0 as falsey, and all positive integers as truthy. Commented May 24, 2021 at 20:38
  • 1
    @JavaSheriff, what do you mean? That was an example, in my earlier comment. Other than replacing the ... with actual content of the then block, it needs no changes, as long as your $1 is 0 for false and 1 for true. Commented Jun 7, 2021 at 17:43

1 Answer 1

3

The accepted answer on the linked post starts with:

bash doesn't know boolean variables, nor does test

So, as stated in the comments[1][2] if [ "$1" ]; is evaluated to if [ -n "$1" ], and since $1 isn't empty, "Parameter is true" will be printed.


To test if the string "true" is given, you can use the following code

#!/bin/bash

copyFile() {
    echo "copyFile #Parameter:$1"

    if [ "$1" = "true" ]; then
    echo "Parameter is true"
    else
        echo "Parameter is false"
    fi
}

copyFile "true"
copyFile "false"

This will produce:

copyFile #Parameter:true
Parameter is true
copyFile #Parameter:false
Parameter is false

as you can test on this online demo.

1
  • 3
    == should be =. As this is it works for bash itself but not for baseline POSIX shells. See the POSIX standard for test, which doesn't specify == at all. Commented May 24, 2021 at 20:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.