英文:
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]="$uid"
done < <(cut -d":" -f3 /etc/passwd)
Modifying OP's current code to test if $num
is an element in the array:
while true; do
read -p "Enter a number between 1000 and 59999: " num
echo ""
if [[ "$num" -gt 1000 && "$num" -lt 60000 ]]; then
if [[ -n "${uids[num]}" ]]; 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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论