m-chrzan.xyz
aboutsummaryrefslogtreecommitdiff
path: root/bash.md
blob: 41e8f0579ea2123153c0baa9d85794fb7e4311c5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# Bash scripting

## String manipulation

Remove shortest from end

    ${VAR%substr}
    # e.g.
    ${FILEPATH%.*}.out   # change extension from whatever to .out

Remove longest from start

    ${VAR##substr}
    # e.g.
    ${FILEPATH##*/}      # get only file name portion

%% - longst from end, # - shortest from start

## Control flow

Loop over files

    for file in glob/*; do something $file; done

Loop over integers

    for i in `seq 10`; do echo $i; done

## Conditionals

* `-z`: is empty string
* `-n`: non-empty string
* `-f`: is regular file
* `$A == $B`: string equality, accepts globs
* `$A != $B`: string inequality

## Heredocs

    cat << EOF > file
    bla bla
    EOF

Ignoring the initial indent:

    ...
        cat <<- EOF > file
        bla bla
        EOF
    ...

Don't interpolate variables:

    cat << 'EOF' > file
    bla bla
    EOF