Issue
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?
Solution
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.
Answered By - 0stone0