gnu bash script and general code optimisation tips

Over the years that I have been programming I had quite a few moments when I had to optimise code, so today I have decided to share how I do it, you might find this useful

# BASH script optimisation

Note: A lot of these points can be also applied to the next section

# General code optimisation

# Examples

# Example 1

x="$(cat -- /etc/passwd)"

Faster:

x="$(</etc/passwd)"

# Example 2

greet() { echo "Hello, $1"; }

x="$(greet 'ari')"
echo "$x"

Faster:

greet() {
    local -n _r="$1"
    shift 1

    printf -v _r "Hello, %s" "$1"
}

greet x 'ari'
echo "$x"

# Example 3

x="Hel o"
echo "$x" | sed 's/ /l/'

Faster:

x="Hel o"
echo "${x/ /l}"

# Example 4

printf '%s\n' 'hey'

Faster:

echo 'hey'

# Example 5

x=()

while read -r line; do
    x+=("$line")
done <file

Faster:

mapfile -t x <file

# Example 6

sed '1!d' file

Faster:

head -n1 file

# Example 7

id >/tmp/x
echo "Info: $(</tmp/x)"
rm -f /tmp/x

Faster:

echo "Info: $(id)"

# Example 8

for _ in $(seq 10000); do
    echo "Hello"$'\n'"world"
done

Faster:

nl=$'\n'

for _ in $(seq 10000); do
    echo "Hello${nl}world"
done

# Example 9

while read -r line; do
    echo "$line"
done <file

Faster:

echo "$(<file)"

# Example 10

format ELF64 executable 3
segment readable executable

_start:
    ;; 2 syscalls per char

    mov eax, 0
    mov edi, 0
    mov esi, buf
    mov edx, 1
    syscall

    test eax, eax
    jz .exit

    mov eax, 1
    mov edi, 1
    mov esi, buf
    mov edx, 1
    syscall

    jmp _start

.exit:
    mov rax, 60
    mov rdi, 0
    syscall

segment readable writable
    buf: rb 1

Faster:

format ELF64 executable 3
segment readable executable

_start:
    ;; 2 syscalls per 1024 chars

    mov eax, 0
    mov edi, 0
    mov esi, buf
    mov edx, 1024
    syscall

    test eax, eax
    jz .exit

    mov edx, eax

    mov eax, 1
    mov edi, 1
    mov esi, buf
    syscall

    jmp _start

.exit:
    mov rax, 60
    mov rdi, 0
    syscall

segment readable writable
    buf: rb 1024

# Example 11

int x = 0;
x = 0;
x = 1;
x--;
x++;

Faster:

int x = 1;

# Example 12

content="$(cat /etc/passwd)"

Faster:

content="$(</etc/passwd)"

Faster:

mapfile -d '' content </etc/passwd
content="${content[*]%$'\n'}"

Faster:

read -rd '' content </etc/passwd

^ This exists with code 1, so just add a || : at the end if that's unwanted behaviour