Input = ./q4.sh https://cdn.eso.org/images/thumb700x/eso1723a.jpg
echo $1 | grep -i "https://" $1 2> /dev/null || echo $1 | grep -i "http://" $1 2> /dev/null || echo 'Ce script supporte seulement les URLs commencant par https:// ou http://' && exit 1
輸出總是跳到最后|| echo 'Ce script supporte seulement les URLs commencant par https:// ou http://'
即使我的論點 1 有 http:// 或 https://
uj5u.com熱心網友回復:
這可能會讓你走上正確的道路
echo "$1" | grep -Eiq '^https?://' 2>/dev/null || echo "fail"
uj5u.com熱心網友回復:
假設不失一般性,您的腳本是用一個引數呼叫的http://something:
echo $1 | grep -i "http://" $1不在管道輸出http://的字串中查找,因為忽略了它的標準輸入,而是讀取由引數命名的檔案。因此它試圖讀取一個名為當然不存在的檔案。但是,由于您已經重定向了會告訴您這消失的錯誤訊息,因此您只會收到抱怨 URL 的訊息并退出。http://somethingechogrep option(s) regexp argumenthttp://something2>/dev/null
這樣做echo $1 | grep -i "http://"(對于 https 也是如此)會起作用,但非常笨拙。它還將(匹配的)URL 輸出到您沒有重定向的標準輸出,因此它可能會出現在您的終端上,這可能是您想要的,也可能不是您想要的。通常,echo "$1" ...只要引數可能包含空格(或其他 IFS 分隔符)或任何通配符(glob)字符,您就應該使用它,但是有效的 URL 不能做第一個,幾乎永遠不會做最后一個,所以在這種特定情況下它不太重要.
此外,該 grep將匹配并因此接受包含http:// 或 https:// 但不以它開頭的 URL ,因為需要回顯訊息狀態。如果您只想在開頭匹配,請^在正則運算式中使用。
更有效的解決方案是使用來自 herestring 的輸入的單個 grep(^https?在擴展模式下表示“http 或 https,但僅在開始時”):
grep -Ei "^https?://" <<<$1 || echo "URL must begin ..." && exit 1
# if you don't want the matched URL output on stdout,
# either redirect [1]>/dev/null or add q to the options (-Eiq)
如果您可以僅使用小寫字母(實際上這是人們總是用于 URL 方案的,即使標準說應該接受大寫字母),效率更高(根本沒有 grep)是:
case $1 in (http://* https://*) ;; (*) echo "URL must begin ..." ... ; esac
uj5u.com熱心網友回復:
如果您需要不區分大小寫的匹配
shopt -s nocasematch
if [[ ! "$1" =~ ^https?:// ]]
then
echo 'ERROR' >&2
fi
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/441512.html
上一篇:使用awk在字串中查找值
下一篇:jq帶單引號bash腳本
