Storing data in an array (bash scripting)

时间:2015-05-12 23:06:56

标签: bash unix scripting

I want to ask a user for an input such as:

matches = []
def subber(m):
    matches.append(m.groups()[0])
    return ""

new_text = re.sub("\[(.*?)\]",subber,s)
print new_text
print matches

The idea is to keep asking for name and name2 and print them all at the end depending on the Y/N answer.

But how do I store them into different variables?**

There may be 20 names and some are costumer and some employer.

P.S.:

To clear any confusion, if there is any, AreYouDone is just a function that'll just exit out of the program when the costumer is done and implemented already.

Thanks.

2 个答案:

答案 0 :(得分:2)

Declare array/s.

Example:

donutData.push({label: '@activity', value: @steps});

Additionally (from comment): You can construct a full sentence with another declare -a names for ((i=0;i<20;i++));do read -rp "Enter name: " 'names[i]' echo "${names[i]}" done loop with the inputs you got:

for

As for ((i=0;i<${#names[@]};i++));do fullsentence+="Name is ${names[$i]} " done echo "$fullsentence" is an indexed array, you can access its value at a certain index with names, where ${names[$i]} is the index. $i is the size of the array.

答案 1 :(得分:2)

听起来你想要两个阵列 - 一系列客户和一系列雇主。

declare -a customers=( ) employers=( )
while ! AreYouDone; do
  echo "Please enter name: "
  read name 
  read -r -p "Is this a costumer? (Y/N)" response;
  if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]; then 
      customers+=( "$name" )
  else
      employers+=( "$name" )
  fi
done

然后,按类型打印所有名称:

printf '%s is a customer\n' "${customers[@]}"
printf '%s is an employer\n' "${employers[@]}"

更高级的方法是使用关联数组来存储每个名称的类型信息。

declare -A names=( )
while ! AreYouDone; do
  read -r -p "Please enter name: " name
  read -r -p "Is this a customer? " type
  if [[ $response = [Yy][Ee][Ss] ]]; then
    names[$name]=customer
  else
    names[$name]=employer
  fi
done

for name in "${!names[@]}"; do
  echo "$name is a ${names[$name]}"
done

除此之外:如果你想更好地控制AreYouDone之后发生的事情,最好这样写:

AreYouDone() {
  read -r -p 'Are you done?'
  case $REPLY in
    [Yy]*) return 0 ;;
    *)     return 1 ;;
  esac
}

...让它返回true或false值,具体取决于用户是否要退出,而不是让它自行退出。