[英]How do I set a default action for when the URL passed to lynx is invalid?
我的目標是編寫一個小的bash腳本,將給定PHP函數的手冊頁的內容輸出到終端。 我當前的腳本( pfunc )如下:
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi
到目前為止,它正在按預期工作:
me@mybox:~$ pfunc rand | head -17
產生
rand — Generate a random integer
Description
int rand ( void )
int rand ( int $min , int $max )
If called without the optional min, max arguments rand() returns a
pseudo-random integer between 0 and [74]getrandmax(). If you want a
random number between 5 and 15 (inclusive), for example, use rand(5,
15).
Note: On some platforms (such as Windows), [75]getrandmax() is only
32767. If you require a range larger than 32767, specifying min and
max will allow you to create a range larger than this, or consider
using [76]mt_rand() instead.
每當傳遞無效的URL時,我都會打印一條消息,例如“ PHP中不存在該函數”之類的消息,而不是靜默返回命令提示符。 誰能提供一些關於如何執行此操作的見解? 提前致謝。
無論查詢是否成功,PHP.net都會返回成功的響應,因此您無法像在行為良好的網站中那樣檢查HTTP狀態代碼。
您可以改為使用kludge:
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
if [[ $contents == *"doesn't exist. Closest matches"* ]]
then
echo "No such function" >&2
else
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi
fi
我會根據您的腳本做什么:
#!/bin/bash
if [ -z "$1" ]
then
echo
echo "No function specified"
echo
echo "pfunc command syntax: pfunc <function>"
echo
echo "Example: pfunc func_get_args"
echo
exit 1
else
func=$1
url="http://php.net/$func"
contents=$(lynx -dump $url)
if [[ $contents =~ $func[[:space:]]+doesn.t[[:space:]]+exist.[[:space:]]+Closest[[:space:]]+matches ]]
then
echo >&2 "php.net don't have a page for $func"
exit 1
fi
clear
awk -v a="$contents" -v b="$func" 'BEGIN{gsub(/\"\n\"/, "\"\\n\"", a); print substr(a, index(a, b" —"), index(a, "See Also") - index(a, b" —"))}'
fi
您可以解析lynx的響應(或其他方式,如wget,curl,lwp-request)以確定該函數是否不存在。
lwp-request的示例:
[neumann@MacBookPro ~]$ GET "http://php.net/$func"|grep "<b>$func</b> doesn'\t exist"
<b>toto</b> doesn't exist. Closest matches:
[neumann@MacBookPro ~]$ func=preg_match
[neumann@MacBookPro ~]$ GET "http://php.net/$func"|grep "<b>$func</b> doesn'\t exist"
[neumann@MacBookPro ~]$
因此,您可以嘗試執行以下操作:
existFunction(){
lwp-request -mget "http://php.net/$1"|grep "<b>$1</b> doesn'\t exist" >/dev/null || echo "1"
}
if [[ $(existFunction $1) = 1 ]]; then
echo "YES"
fi
注意:GET是“ lwp-request -mget”的別名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.