Check if uid numbers in /etc/passwd are in a certain range and not already used, with nested ifs

huangapple go评论52阅读模式
英文:

Check if uid numbers in /etc/passwd are in a certain range and not already used, with nested ifs

问题

我正在尝试检查已经使用并在1000到60000范围内的uid,使用了嵌套的if条件,但只有范围条件起作用。
此外,它打印了$hpass的内容。
有什么改进代码的想法吗?

提前感谢任何建议!

以下是我的代码:

#!/bin/bash
dbpasswd=$(cat /etc/passwd | cut -d ":" -f3 | sort -n)
hpass=$(printf '%d\n' "$dbpasswd")  #将所有数字放在单独的行上
while true; do
read -p "输入一个介于1000到59999之间的数字" num
echo ""
if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
   if [[ "$num" -eq "$hpass" ]]; then 
   echo "$num 已经在使用中"
   else
   echo "$num 在范围内且尚未使用!"
   break
   fi
else
   echo "$num 超出范围"
fi
done
英文:

I am trying to check the uid's that are already used and in within a range from 1000 to 60000, with nested if conditions but only the range condition works.
Also it prints the $hpass content.
Any ideas how to improve the code?

Thanks in advance for any suggestions!

Here is my code:

#!/bin/bash
dbpasswd=$(cat /etc/passwd | cut -d ":" -f3 | sort -n)
hpass=$(printf '%d\n' "$dbpasswd")  #to put all numbers on separeate line
while true; do
read -p "Enter a number between 1000 and 59999" num
echo ""
if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
   if [[ "$num" -eq "$hpass" ]]; then 
   echo "$num is already in use"
   else
   echo "$num is in range and not yet used!"
   break
   fi
else
   echo "$num is out of range"
fi
done

答案1

得分: 2

加载/etc/passwd文件中的UID列表到一个数组中:

uids=()

while read -r uid
do
    uids[$uid]="$uid"
done < <(cut -d":" -f3 /etc/passwd)

修改OP的当前代码以测试$num是否是数组中的元素:

while true; do
    read -p "输入一个介于1000和59999之间的数字: " num
    echo ""
    
    if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
        if [[ -n "${uids[num]}" ]]; then 
            echo "$num 已被使用"
        else
            echo "$num 在范围内且尚未被使用!"
            break
        fi
    else
        echo "$num 超出范围"
    fi
done
英文:

Load the list of /etc/passwd uids into an array:

uids=()

while read -r uid
do
    uids[$uid]=&quot;$uid&quot;
done &lt; &lt;(cut -d&quot;:&quot; -f3 /etc/passwd)

Modifying OP's current code to test if $num is an element in the array:

while true; do
    read -p &quot;Enter a number between 1000 and 59999: &quot; num
    echo &quot;&quot;

    if [[ &quot;$num&quot; -gt 1000 &amp;&amp; &quot;$num&quot; -lt 60000 ]]; then
        if [[ -n &quot;${uids[num]}&quot; ]]; then 
            echo &quot;$num is already in use&quot;
        else
            echo &quot;$num is in range and not yet used!&quot;
            break
        fi
    else
        echo &quot;$num is out of range&quot;
    fi
done

huangapple
  • 本文由 发表于 2023年6月25日 23:29:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551148.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定