ubuntu – How to set a toggle on linux (True or False) bash command?

Presumably something like this:

status=$(gsettings get "$class" "$name")
status=${status,,} # normalize to lower case; this is a modern bash extension
if [[ $status = true ]]; then
gsettings set "$class" "$name" "$new_status"

Breaking it down into pieces:

  • #!/bin/bash ensures that the interpreter for this script is bash, enabling extended syntax such as [[ ]].
  • The syntax $( ) is “command substitution”; this runs a command, and substitutes the output of that command. Thus, if the output is true, then status=$(...) becomes status=true.
  • The parameter expansion ${name,,} expands the contents of name while converting those contents to all-lowercase, and is only available in newer versions of bash. If you want to support /bin/sh or older releases of bash, consider status=$(printf '%sn' "$status" | tr '[:upper:]' '[:lower:]') instead, or just remove this line if the output of gsettings get is always lowercase anyhow.
  • The comparison [[ $status = true ]] relies on the bash extension [[ ]] (also available in other modern ksh-derived shells) to avoid the need for quoting. If you wanted it to work with #!/bin/sh, you’d use [ "$status" = true ] instead. (Note that == is allowable inside [[ ]], but is not allowable inside of [ ] on pure POSIX shells; this is why it’s best not to be in the habit of using it).

Note that whitespace is important in bash! foo = bar, foo= bar and foo=bar are completely different statements, and all three of them do different things from the other two. Be sure to be cognizant of the differences in copying from this example.


(Visited 1 times, 1 visits today)