Bash If statement in Case statement to output boolean value not working
I have the following Bash script:
#!/bin/bash
input=true
input="$($(IFS=, read -r s ; echo "${s}bool") <<< "$input")"
IFS=,; set -f; set -- $input; out=
for i in "$@"; do case "$i" in "") echo "empty input not allowed" exit 0 ;; *bool) if [[ "${s}" == "true" || "${s}" == "false" ]]; then out="$out,${i/%bool/}" else echo "value not allowed" && exit 0 fi ;; esac
done
echo "${out:1}"The input is from a TUI interface and the output will be used in an SQL insert statement as a boolean value. This is a simplified version of a larger script, hence the for loop and case statement. If I run the script I get no output at all and no error message.
What I am trying to achieve is that I get either true or false as output depending on whether $input is true or false. Please ignore "") in the case statement.
Can someone please help?
11 Answer
If I run the script I get no output at all and no error message.
You should (unless you are a bash expert) take advantage of ShellCheck – shell script analysis tool when you are having problems with your scripts.
Running your script through ShellCheck returns the following errors:
$ shellcheck myscript
Line 5:
input="$((IFS=, read -r s ; echo "${s}bool" )<<<"$input")" ^-- SC1102: Shells disambiguate $(( differently or not at all. For $(command substition), add space after $( . For $((arithmetics)), fix parsing errors. ^-- SC2030: Modification of s is local (to subshell caused by (..) group).
Line 7:
IFS=,; set -f; set -- $input; out= ^-- SC2086: Double quote to prevent globbing and word splitting.
Did you mean: (apply this, apply all SC2086)
IFS=,; set -f; set -- "$input"; out=
Line 12: *bool) if [[ "${s}" == "true" || "${s}" == "false" ]] ; then out="$out,${i/%bool/}" else echo "value not allowed" && exit 0 ; fi;; ^-- SC2031: s was modified in a subshell. That change might be lost. ^-- SC2031: s was modified in a subshell. That change might be lost.
$ Fix the errors and then check the script again.
Rinse and recycle until your script is working.