The commands
new=$(openssl rand -hex 20); …apply it…; unset new # generate
install -m 400 old.txt /srv/secrets/app/token # move a file
key=$(sed -nE 's/.*apiKey: *"?([^"]+)"?.*/\1/p' cfg.yml); printf '%s' "$key" > /srv/secrets/app/key; unset key
wc -c < /srv/secrets/app/key # check it's not empty — by size
$(…) puts the value into a variable, and nothing is printed. Shell history keeps the command with $new and
$key, not the values.
printf '%s' writes without a trailing newline: some programs read the key together with \n and reject it.
Where to keep secrets on the server and how to attach them to containers — Secrets in Docker stacks.