Home > other >  Avoid repeating variable setup in bash
Avoid repeating variable setup in bash

Time:05-24

Bash newbie here! How do I avoid repeating the "PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)" each time in this bash script excerpt?

sqlite variables.db "create table passwords (name TEXT PRIMARY KEY, value TEXT);"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('BOOKSTACK_MYSQL_ROOT', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('BOOKSTACK_MYSQL', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('BORG_PASSPHRASE', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('CODE_SERVER_PASS', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('CODE_SERVER_SUDO_PASS', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('EXPORTARR_TOKEN', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('FLAME_PASS', '$PASSGEN');"
PASSGEN=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
sqlite variables.db "insert into passwords (name,value) values ('FLIGHTAIRMAP_INSTALL_PASS', '$PASSGEN');"

CodePudding user response:

A simple solution would be to write a function:

function generate_password {
    </dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12
}

Then, your code snippet becomes:

sqlite variables.db "create table passwords (name TEXT PRIMARY KEY, value TEXT);"
sqlite variables.db "insert into passwords (name,value) values ('BOOKSTACK_MYSQL_ROOT', '$(generate_password)');"
sqlite variables.db "insert into passwords (name,value) values ('BOOKSTACK_MYSQL', '$(generate_password)');"
sqlite variables.db "insert into passwords (name,value) values ('BORG_PASSPHRASE', '$(generate_password)');"
# ...

CodePudding user response:

One way to do it is to use a loop for the table insertions. Try this Shellcheck-clean code:

sqlite variables.db "create table passwords (name TEXT PRIMARY KEY, value TEXT);"

for name in BOOKSTACK_MYSQL_ROOT BOOKSTACK_MYSQL BORG_PASSPHRASE    \
            CODE_SERVER_PASS CODE_SERVER_SUDO_PASS EXPORTARR_TOKEN  \
            FLAME_PASS FLIGHTAIRMAP_INSTALL_PASS
do
    passgen=$(</dev/urandom tr -dc _A-Z-a-z-0-9 | head -c12)
    sqlite variables.db "insert into passwords (name,value) values ('$name', '$passgen');"
done
  • Related