如果条目已经存在,我怎么能出错?
How can i error out an entry if it already exists?
我正在编写一个简单的程序来将联系人添加到名为 "phonebook" 的文件中,但如果该联系人已经存在,我希望它 return 回显说“(姓氏name) 已经存在”,而不是将其添加到文件中。到目前为止,我已经获得了添加用户的程序,但它不会 return 回显并添加重复条目。我该如何解决这个问题?
#!/bin/bash
# Check that 5 arguments are passed
#
if [ "$#" -ne 5 ]
then
echo
echo "Usage: first_name last_name phone_no room_no building"
echo
exit 1
fi
first=
last=
phone=
room=
building=
# Count the number of times the input name is in add_phonebook
count=$( grep -i "^$last:$first:" add_phonebook | wc -l )
#echo $count
# Check that the name is in the phonebook
if [ "$count" -eq 1 ]
then
echo
echo "$first $last is already in the phonebook."
echo
exit 1
fi
# Add someone to the phone book
#
echo " " >> add_phonebook
# Exit Successfully
exit 0
两件事:
在尝试 grep 之前应该检查 add_phonebook 文件是否存在,否则你会得到 grep: add_phonebook: No such file or directory
输出。
您的 grep 表达式与文件格式不匹配。
您在字段之间使用 space 保存文件,但在名称之间使用冒号 (:) 进行搜索。您可以更新文件格式以使用冒号分隔字段,或更新 grep 表达式以在 space 上搜索。此外,您保存名字 last_name,但搜索 last_name、first_name。
使用 space 格式:
count=$( grep -i "^$last[[:space:]]\+$first[[:space:]]" add_phonebook | wc -l )
从回显行中删除了我的制表符分隔符,使用了空格,现在它可以正确计数了
我正在编写一个简单的程序来将联系人添加到名为 "phonebook" 的文件中,但如果该联系人已经存在,我希望它 return 回显说“(姓氏name) 已经存在”,而不是将其添加到文件中。到目前为止,我已经获得了添加用户的程序,但它不会 return 回显并添加重复条目。我该如何解决这个问题?
#!/bin/bash
# Check that 5 arguments are passed
#
if [ "$#" -ne 5 ]
then
echo
echo "Usage: first_name last_name phone_no room_no building"
echo
exit 1
fi
first=
last=
phone=
room=
building=
# Count the number of times the input name is in add_phonebook
count=$( grep -i "^$last:$first:" add_phonebook | wc -l )
#echo $count
# Check that the name is in the phonebook
if [ "$count" -eq 1 ]
then
echo
echo "$first $last is already in the phonebook."
echo
exit 1
fi
# Add someone to the phone book
#
echo " " >> add_phonebook
# Exit Successfully
exit 0
两件事:
在尝试 grep 之前应该检查 add_phonebook 文件是否存在,否则你会得到 grep: add_phonebook: No such file or directory
输出。
您的 grep 表达式与文件格式不匹配。
您在字段之间使用 space 保存文件,但在名称之间使用冒号 (:) 进行搜索。您可以更新文件格式以使用冒号分隔字段,或更新 grep 表达式以在 space 上搜索。此外,您保存名字 last_name,但搜索 last_name、first_name。
使用 space 格式:
count=$( grep -i "^$last[[:space:]]\+$first[[:space:]]" add_phonebook | wc -l )
从回显行中删除了我的制表符分隔符,使用了空格,现在它可以正确计数了