我对 Bash 脚本世界有些陌生,并且仍在尝试了解大多数人认为的基础知识。我找到了 this helpful guide我一直从中提取大部分信息,尽管它指的是“高级”,但它实际上涵盖了像我这样的新手的基础知识。
至此,我已经编写了一个可以按我希望的方式运行的脚本,但我想我是某些人可能认为具有代码意识的人。因此,虽然我的脚本确实有效,但我认为我没有正确使用 Bash 的 if/then/else 语句。
这是我编写的小脚本,主要通过 API 查询检查用户名以及它们是否存在。它允许用户通过 ./script.sh list
定义列表,或者如果他们没有定义列表,它只是尝试字母的所有变体({a..z}
):
#!/bin/bash
# variables
host='https://api.example.com/api/users/'
sleep=1
# check if jq install
if ! jq_loc="$(type -p "jq")" || [ -z "$jq_loc" ]; then
echo "no jq installed."
sleep 1
echo "we're going to install it now."
sleep 2
sudo apt-get install jq
fi
# specified list
if [ -n "$1" ] ; then
list=`cat $1`
for username in $list
do
#echo $username
sleep $sleep
VAL=`curl -s "$host$username" | jq -r ".id" | grep null`
#echo $VAL
if [[ $VAL == null ]]
then
echo -e "$username is available"
echo "$username" >> username.free
else
echo -e "$username is taken"
fi
done
fi
# no list specified
if [ $# -eq 0 ] ; then
list=`echo {a..z}{a..z}{a..z}`
for username in $list
do
#echo $username
sleep $sleep
VAL=`curl -s "$host$username" | jq -r ".id" | grep null`
#echo $VAL
if [[ $VAL == null ]]
then
echo -e "$username is available"
echo "$username" >> username.free
else
echo -e "$username is taken"
fi
done
fi
正如我所说,该脚本完全符合我的要求。但我关心的是 if [ $# -eq 0 ] ; then
和 if [ -n "$1" ] ; then
.我觉得我在呼应它不必要地执行相同的功能。例如,不必告诉它执行 curl
每个if
中的命令, 有什么办法可以合并这两个 if
变成一个?
希望我已经解释得足够好,如果没有,请发表评论,我可以相应地更新这个问题。
提前致谢!
最佳答案
您的 if 语句涵盖所有逻辑分支。因此,以下代码块将以任何一种方式执行。所以没有理由复制它。只需将其移至 if 语句下方即可。
for username in $list
do
#echo $username
sleep $sleep
VAL=`curl -s "$host$username" | jq -r ".id" | grep null`
#echo $VAL
if [[ $VAL == null ]]
then
echo -e "$username is available"
echo "$username" >> username.free
else
echo -e "$username is taken"
fi
done
这是为减少重复而重新编写的代码:
#!/bin/bash
# variables
host='https://api.example.com/api/users/'
sleep=1
# check if jq install
if ! jq_loc="$(type -p "jq")" || [ -z "$jq_loc" ]; then
echo "no jq installed."
sleep 1
echo "we're going to install it now."
sleep 2
sudo apt-get install jq
fi
if [ -n "$1" ] ; then
# specified list
list=`cat $1`
else
# no list specified
list=`echo {a..z}{a..z}{a..z}`
fi
for username in $list
do
#echo $username
sleep $sleep
VAL=`curl -s "$host$username" | jq -r ".id" | grep null`
#echo $VAL
if [[ $VAL == null ]]
then
echo -e "$username is available"
echo "$username" >> username.free
else
echo -e "$username is taken"
fi
done
关于linux - 使用 If/Then/Else 语句整合 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42727465/