-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?

anubhava
  • 761,203
  • 64
  • 569
  • 643
JavaSheriff
  • 7,074
  • 20
  • 89
  • 159
  • 4
    Hint: `false` is just a string and it is not empty – anubhava May 24 '21 at 20:04
  • hmm Thank you! is there a way to force convert it to Boolean? – JavaSheriff May 24 '21 at 20:08
  • 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 … – Jonathan Leffler May 24 '21 at 20:10
  • 1
    Remove `[` and `]`. – Cyrus May 24 '21 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. – Charles Duffy May 24 '21 at 20:38
  • @CharlesDuffy can you please post an example? thank you very much! – JavaSheriff Jun 07 '21 at 17:40
  • 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. – Charles Duffy Jun 07 '21 at 17:43

1 Answers1

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.

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 3
    `==` should be `=`. As this is it works for bash itself but not for baseline POSIX shells. See [the POSIX standard for `test`](https://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html), which doesn't specify `==` at all. – Charles Duffy May 24 '21 at 20:35