使用 Grep 命令显示退出状态的 Shell 脚本
Linux 为用户提供了命令行工具的一个很棒的很酷的功能以及一个图形用户界面,他们可以在其中通过破坏命令来执行任务。所有这些命令都会根据它们的执行情况返回一个状态。它的执行值可用于显示错误或在 shell 脚本中执行一些其他操作。
退出状态根据其执行情况如下
- 命令已成功执行:0(退出状态值)
- 命令失败:1 – 255(退出状态的值将为 b/w 1 到 255)
退出状态:每个 Linux 命令在执行后都有退出状态。它的值可以通过调用 $? (外壳变量)。它给出了先前执行的命令的值。
Note: Command for printing exit status for privious command: echo $?
在本文中,将编写一个 shell 脚本来使用grep命令显示退出状态。它将显示一个 shell 脚本示例来显示退出状态。
方法:
要为此编写脚本代码,请按照以下步骤操作
- 使用 touch 命令创建数据库,它是一个名为 gfg.txt 的文本文件。
- 现在从用户那里获取密钥,如果他想将其插入数据库或检查该书是否存在于数据库中(意味着该书已阅读或未阅读)。
- 现在根据选择的键制作 if-else 块并从用户那里读取书名。
- 在第一个条件下,使用grep命令检查书籍的可用性并获取退出状态值并检查是否为 0。第二个条件只是获取书名并将名称添加到数据库中。
- 现在,根据上一条命令的退出状态值打印已读书籍的状态。
外壳脚本代码:
# shell script for display exit status by using grep command
# make an file gfg.txt to contain the book name of user that he has read
touch gfg.txt
# now print user to tell him the scenerio
echo "Please, enter the some of your book name that you
have read or a book name that you want to know read status of that book"
echo
# print the key to ask user find the book or write the book name
echo "Please enter a key like following"
echo "Enter 1 to know the book read status"
echo "Enter 2 to write the book name in book database ( gfg.txt )"
# read the entered key
read key
echo
# check the condition using if-else statement
if [[ $key == 1 ]]
then
# loop to get the name of book continuously
while [ 1 ]
do
# print the initial statement
echo "Enter book name about that you want to know read status or -1 for exit"
# read the book name and find in gfg.text using grep command
read bookName
# check condition to break the loop
if [[ $bookName == -1 ]]
then
break
else
# now find the book in gfg.text
count=$(grep -c "$bookName" gfg.txt)
# get the exit status of the privous command
exitStatus=$?
# check the value of exitStatus and print output according that
if [[ $exitStatus == 0 ]]
then
# give the msg to user that he have read that book
echo "Your privious command exit status is $exitStatus"
echo "You have read the $bookName book."
echo
else
# give the msg to user that he didn't read that book yet.
echo "Your privious command exit status is $exitStatus"
echo "You didn't read $bookName book yet."
echo
fi
fi
done
else
# loop to get the name of books continuously
while [ 1 ]
do
echo "Enter book name that you want write in database (gfg.txt) or -1 for exit"
# read the name of book
read bookName
# check the condition to break the loop
if [[ $bookName != -1 ]]
then
# write the book name in text file
echo $bookName >> gfg.txt
else
break
fi
echo
done
fi
在第一个示例中将显示数据库中插入的书名(gfg.text)。
在第二个示例中将了解检查书籍阅读状态(使用 grep 命令进行内部检查和退出状态):