【问题标题】:Calling one variable before another [duplicate]在另一个变量之前调用一个变量[重复]
【发布时间】:2020-12-13 22:23:48
【问题描述】:

如果有意义的话,我需要在 $user 变量之前调用 $i 变量,以便将两者的组合称为一个变量。感谢您的帮助。

declare -i numusers
echo "How many (non-admin) users? ex: 01 02 10"
read numusers
i=0
while [[ $i -lt $numusers ]] ; do
   echo "enter name of user$i - "
   read user$i
   echo "user$i recored as - $user$i  - "
  (( i += 1 ))
done

【问题讨论】:

  • 调用”变量是什么意思?您可以调用一个函数,或扩展一个变量。顺便说一句:$user$i 将分别扩展 useri,所以你基本上得到了变量值的串联。

标签: bash


【解决方案1】:

我认为您正在寻找一个用于存储用户名的数组。这对您有用吗?

#!/bin/bash

declare -i numusers
echo "How many (non-admin) users? ex: 01 02 10"
read numusers
i=0
while [[ $i -lt $numusers ]] ; do
   echo "enter name of user$i - "
   read user[$i]
   echo "user$i recored as - ${user[$i]}  - "
  (( i += 1 ))
done

【讨论】:

  • How to Answer 中,请注意“回答正确提出的问题”部分,其中的要点是关于“之前已被多次询问和回答”的问题。
  • 顺便说一句,我建议引用 user[$i],因此如果当前目录中存在任何匹配的文件名,或者用户应该拥有 nullglob、@987654325 @ 或类似选项启用告诉 shell 在存在看起来像 glob 但不匹配任何文件的表达式时具有非默认行为。比这更好的是,根本不用维护索引变量; users=( ); while (( ${#users[@]} < numusers )) && IFS= read -r newUser; do users+=( "$newUser" ); done
猜你喜欢
  • 2012-07-19
  • 1970-01-01
  • 1970-01-01
  • 2020-01-10
  • 2013-11-04
  • 2018-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-10-09
相关资源
最近更新 更多