pure-bash-bible/manuscript/chapter16.txt

152 lines
2.4 KiB
Plaintext
Raw Normal View History

# Conversion
## Convert a hex color to RGB
**Example Function:**
```sh
hex_to_rgb() {
# Usage: hex_to_rgb "#FFFFFF"
((r=16#${1:1:2}))
((g=16#${1:3:2}))
((b=16#${1:5:6}))
printf '%s\n' "$r $g $b"
}
```
**Example Usage:**
```shell
$ hex_to_rgb "#FFFFFF"
255 255 255
```
## Convert an RGB color to hex
**Example Function:**
```sh
rgb_to_hex() {
# Usage: rgb_to_hex "r" "g" "b"
printf '#%02x%02x%02x\n' "$1" "$2" "$3"
}
```
**Example Usage:**
```shell
$ rgb_to_hex "255" "255" "255"
#FFFFFF
```
# Code Golf
## Shorter `for` loop syntax
```shell
# Tiny C Style.
for((;i++<10;)){ echo "$i";}
# Undocumented method.
for i in {1..10};{ echo "$i";}
# Expansion.
for i in {1..10}; do echo "$i"; done
# C Style.
for((i=0;i<=10;i++)); do echo "$i"; done
```
## Shorter infinite loops
```shell
# Normal method
while :; do echo hi; done
# Shorter
for((;;)){ echo hi;}
```
## Shorter function declaration
```shell
# Normal method
f(){ echo hi;}
# Using a subshell
f()(echo hi)
# Using arithmetic
# You can use this to assign integer values.
# Example: f a=1
# f a++
f()(($1))
# Using tests, loops etc.
# NOTE: You can also use while, until, case, (()), [[]].
f()if true; then echo "$1"; fi
f()for i in "$@"; do echo "$i"; done
```
## Shorter `if` syntax
```shell
# One line
# Note: The 3rd statement may run when the 1st is true
[[ "$var" == hello ]] && echo hi || echo bye
[[ "$var" == hello ]] && { echo hi; echo there; } || echo bye
# Multi line (no else, single statement)
# Note: The exit status may not be the same as with an if statement
[[ "$var" == hello ]] && \
echo hi
# Multi line (no else)
[[ "$var" == hello ]] && {
echo hi
# ...
}
```
## Simpler `case` statement to set variable
We can use the `:` builtin to avoid repeating `variable=` in a case
statement. The `$_` variable stores the last argument of the last
successful command. `:` always succeeds so we can abuse it to store the
variable value.
```shell
# Modified snippet from Neofetch.
case "$OSTYPE" in
"darwin"*)
: "MacOS"
;;
"linux"*)
: "Linux"
;;
*"bsd"* | "dragonfly" | "bitrig")
: "BSD"
;;
"cygwin" | "msys" | "win32")
: "Windows"
;;
*)
printf '%s\n' "Unknown OS detected, aborting..." >&2
exit 1
;;
esac
# Finally, set the variable.
os="$_"
```
<!-- CHAPTER END -->