How to put environment variable in Array?

梦想与她 提交于 2020-04-18 06:10:08

问题


DIR1, DIR2, .... DIRN are coming from environment variables that contains some directory path. example

export DIR1="/users/abcd"
export DIR2="/users/abcd/xyz"
.
.
.

How do i know that how many DIR_ is in environment variable and put all these in the following array

arr=(DIR1 DIR2 ... . . DIRN)
i=0
while [ $i -lt ${#arr[@]} ] 
do
      cd ${arr[$i]}
      i=`expr $i + 1`
done

回答1:


For the cases when environment variables may contain newlines in their values you can use this script that uses gnu versions of printenv and awk.

mapfile -t arr < <(printenv -0 | awk -v RS='\0' -F= '/^DIR/{print $1}')

Then check your array content as:

declare -p arr



回答2:


"${!prefix@}" expands to the list of variable names that start with prefix. In present circumstances, this can be used as follows:

#!/usr/bin/env bash
[ -n "$BASH_VERSION" ] || { echo "This must be run with bash, not /bin/sh" >&2; exit 1; }

arr=( )
for varname in "${!DIR@}"; do
  [[ $varname =~ ^DIR[[:digit:]]+$ ]] || continue ## skip DIRSTACK or other names that don't match
  arr+=( "${!varname}" )
done



回答3:


My answer refers to the written part of your question, where you ask for environment variables, since from the example you gave, it is not clear whether the variables in question are really environment variables or mere shell variables.

Since printenv gives you a list of environment variables in the form of NAME=VALUE denotations, you can do a

arr=($(printenv|grep '^DIR[0-9]'|cut -f 1 -d =))

The grep picks the lines starting with DIR, followed by at least one digit. Adjust the pattern to your needs.

The cut picks just the left part of the equal sign, i.e. the name.

This solution assumes that you don't have environment variables which contain embedded newlines. In this case, I suggest to use a programming language which gives you a list of environment variables you can loop over. Perl, Ruby or Java would do.




回答4:


printenv   |  awk -F'=' '{if ($0 ~ /^DIR/) print $2; }'

Demo :

:-:export DIR1="/users/abcd"
:-:export DIR2="/users/abcd"
:-:export DIR4="/usasders/abcd"
:-:printenv   |  awk -F'=' '{if ($0 ~ /^DIR/) print $2; }'
/usasders/abcd
/users/abcd
/users/abcd
:-:


来源:https://stackoverflow.com/questions/60666321/how-to-put-environment-variable-in-array

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!