'How to create passwordfile with env variables

In my Programm how can i Iterate trough ENV in bash

if [ ! -z $USER_1 ]
then
  echo "$USER_1":$(openssl passwd -apr1 $PASS_1) > ./passwords
fi
if [ ! -z $USER_2 ]
then
  echo "$USER_2":$(openssl passwd -apr1 $PASS_2) > ./passwords
fi
if [ ! -z $USER_3 ]
then
  echo "$USER_3":$(openssl passwd -apr1 $PASS_3) > ./passwords
fi
if [ ! -z $USER_4 ]
then
  echo "$USER_4":$(openssl passwd -apr1 $PASS_4) > ./passwords
fi
if [ ! -z $USER_5 ]
then
  echo "$USER_5":$(openssl passwd -apr1 $PASS_5) > ./passwords
fi

And so on how can i do it with N "User" when i don't know N



Solution 1:[1]

EDIT April 14: my first version was incomplete, here is a fix.

Create a loop to loop through your users:

#!/bin/bash

USER_1=u1
USER_2=u2

N=5
for (( counter=1; counter<=N; counter++ ))
do
    username=USER_${counter}
    password=PASS_${counter}
    echo "DEBUG: $username"
    echo "DEBUG: ${!username}"
    if [[ -n ${!username} ]]
    then
        #echo "$username:$(openssl passwd -apr1 "$password")"> ./passwords
        echo "DEBUG: USER_${counter} inside if"
    fi
    echo "========="
done
  • To use on your setup, comment out the debug statements and uncomment your openssl line.
  • My first version did not properly user the variable counter inside the other USER_? variable.
  • With this particular script, USER_1 and USER_2 will trigger the if since USER_3 and more are not set.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Konstantin