Home > Enterprise >  How to store dynamic value in Variable For Bash?
How to store dynamic value in Variable For Bash?

Time:08-30

I have below command:

ExpirationDate=$(date -d ' 60 days'  '%Y-%m-%d')
VaultName="abc"
getapp=$(az keyvault secret list --vault-name $VaultName --query "[].{SecretName:name,ExpiryDate:attributes.expires} [?ExpiryDate<='$ExpirationDate']" | jq '.[].SecretName' | tr -d '"')

getserviceprincipal=$(az keyvault secret list --vault-name $VaultName --query "[].{Type:contentType,ExpiryDate:attributes.expires} [?ExpiryDate<='$ExpirationDate']" | jq '.[].Type' | tr -d '"')
     
## get length of $distro array
len=${#getapp[@]}

## Use bash for loop 
for (( i=0; i-le$len-1; i   ))
 do 
 echo "${getapp[$i]}" 
  ./resetpassword.sh -a ${getapp[$i]} -s  ${getserviceprincipal[$i]} -y
 echo "${getserviceprincipal[$i]}" 
 done

in this command I want store all value of vault name getapp and similarly getserviceprincipal. Example If I have more then 2 vault in getapp variable then script is not working due to $getapp is not storing variable in array.

Is anyone help me to put out this simple solutions!! Thanks In Advance..

CodePudding user response:

readarray -t getapp < <( az keyvault ... | tr -d '"' ) should do the trick here.

Note that this requires newlines to be valid delimiters. If there can be newlines in your data then you'll have to pick a different delimiter with the -d delim option. If there isn't any single delimiter that works everywhere then bash may not be the best choice for this.

CodePudding user response:

Since you are using jq, I think you could so something like that:

declare -a getapp=()
declare -a getserviceprincipal=()

# note: be sure to check that the resulting bash is valid!
eval(az keyvault secret list  \
            --vault-name $VaultName  \
            --query "[].{SecretName:name,ExpiryDate:attributes.expires} [?ExpiryDate<='$ExpirationDate']" \
 | jq --raw-output '.[] | @sh "getapp =( \(.SecretName) ) ; getserviceprincipal =( \(.Type) );' ")

If all goes well, this will result in getapp and getserviceprincipal being filled as array: https://jqplay.org/s/BbHMn9i79KB

Note:

  • as you can see, you don't need to invoke your command (az) twice.
  • you can also extract the jq expression to a file using the --from-file option, which may help when reading it and handling shell quotes.
  • Related