我正在尝试编写一个专业程序来通过基于菜单的系统接受和处理输入。该程序应该没有命令行参数。它将被写入名为 TaskMenu 的 csh 脚本中。该 shell 脚本将:
- 向用户索取密码。
A。如果密码不正确,系统将退出 带有适当的错误消息。 - 显示一个文本菜单,然后得到用户的响应。
- 处理用户输入并重新显示文本菜单 直到用户想要退出。
最佳答案
要读取密码,请关闭 echo,读取密码,然后重新启用 echo。 csh:
stty -echo
echo -n "Enter password: "
set password = $<
stty echo
要创建菜单,只需将选项回显到屏幕上,然后 读回一个值。 csh:
echo 1 first item
echo 2 second item
echo 3 third ...
echo -n "Enter Choice: "
set choice = $<
bash 中的这两个任务是:
读取密码:
echo -n "Enter password: "
read -s password
制作菜单:
select choice in "first item" "second item" "third..." do
test -n "$choice" && break;
done
请注意读取密码和制作菜单是如何内置于 bash 中的。除了更容易之外,一些在脚本中完成的常见事情在 csh 中是不可能的。 Csh 并非设计为脚本语言。使用 Bash、Python、Ruby、Perl 甚至是低级的 /bin/sh 编写几行脚本要容易得多。
也就是说,这是一个显示密码和菜单方法的完整 csh 脚本:
#! /bin/csh
set PW="ok"
### Read Password
echo -n "enter passwd: "
stty -echo
set passwd = $<
stty echo
if ( "$passwd" == "$PW" ) then
echo Allrighty then!
else
echo "Try again. Use '${PW}'."
exit 1
endif
### Menu
@ i = 1
set items = (one two three four five six seven)
foreach item ( $items[*] )
echo "${i}) $item"
@ i = $i + 1
end
set choice = 0
while ( $choice < 1 || $choice > $#items )
echo -n "Select: "
set choice = $<
end
echo "You chose ${choice}: $items[$choice]"
注意事项
Though popular for interactive use because of its many innovative features, csh has never been as popular for scripting[1]
关于linux - 用于用户密码验证的 csh 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3694016/