test code with bash
This commit is contained in:
parent
c1ad1593b6
commit
f3d6366c83
1 changed files with 86 additions and 11 deletions
|
|
@ -57,18 +57,93 @@ draft: true
|
|||
|
||||
## 4. Code Blocks with Syntax Highlighting
|
||||
|
||||
```nix
|
||||
{ config, pkgs, ... }:
|
||||
```bash
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
{
|
||||
environment.systemPackages = with pkgs; [
|
||||
git
|
||||
neovim
|
||||
tmux
|
||||
];
|
||||
# Variables & string manipulation
|
||||
NAME="world"
|
||||
GREETING="Hello, ${NAME}!"
|
||||
UPPER=${GREETING^^}
|
||||
SLICE=${GREETING:0:5}
|
||||
echo "$UPPER | $SLICE"
|
||||
|
||||
nix.settings.experimental-features = [ "nix-command" "flakes" ];
|
||||
# Arrays
|
||||
FRUITS=(apple banana cherry)
|
||||
FRUITS+=(mango)
|
||||
echo "${FRUITS[@]}" # all elements
|
||||
echo "${#FRUITS[@]}" # length
|
||||
echo "${FRUITS[@]:1:2}" # slice
|
||||
|
||||
# Associative array
|
||||
declare -A CONFIG=([host]="localhost" [port]="8080")
|
||||
echo "${CONFIG[host]}:${CONFIG[port]}"
|
||||
|
||||
# Arithmetic
|
||||
COUNT=0
|
||||
(( COUNT += 5 ))
|
||||
RESULT=$(( COUNT ** 2 ))
|
||||
echo "$RESULT"
|
||||
|
||||
# Conditionals & test operators
|
||||
FILE="/etc/hosts"
|
||||
if [[ -f "$FILE" && -r "$FILE" ]]; then
|
||||
echo "readable"
|
||||
elif [[ -e "$FILE" ]]; then
|
||||
echo "exists but not readable"
|
||||
else
|
||||
echo "not found"
|
||||
fi
|
||||
|
||||
# Case
|
||||
case "$NAME" in
|
||||
world|earth) echo "planet" ;;
|
||||
*) echo "unknown" ;;
|
||||
esac
|
||||
|
||||
# Loops
|
||||
for fruit in "${FRUITS[@]}"; do
|
||||
echo "fruit: $fruit"
|
||||
done
|
||||
|
||||
for (( i=0; i<3; i++ )); do
|
||||
echo "i=$i"
|
||||
done
|
||||
|
||||
WHILE=3
|
||||
while (( WHILE-- > 0 )); do
|
||||
echo "while: $WHILE"
|
||||
done
|
||||
|
||||
# Functions with local vars & return codes
|
||||
greet() {
|
||||
local name=${1:-"stranger"}
|
||||
local -r greeting="Hi, $name!"
|
||||
echo "$greeting"
|
||||
return 0
|
||||
}
|
||||
greet "$NAME"
|
||||
|
||||
# Command substitution & process substitution
|
||||
DATE=$(date +%Y-%m-%d)
|
||||
DIFF=<(echo "foo")
|
||||
echo "Today: $DATE"
|
||||
|
||||
# Here-doc
|
||||
cat <<EOF
|
||||
Multiline
|
||||
text block
|
||||
EOF
|
||||
|
||||
# Pipelines, redirection & traps
|
||||
trap 'echo "exiting"; exit 1' ERR
|
||||
echo "hello" | tr '[:lower:]' '[:upper:]' > /dev/null 2>&1
|
||||
|
||||
# Parameter expansion: default, error, replace
|
||||
echo "${UNSET:-default}"
|
||||
echo "${GREETING/Hello/Hey}"
|
||||
echo "${FILE##*/}" # basename
|
||||
echo "${FILE%/*}" # dirname
|
||||
```
|
||||
|
||||
---
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue