Bash 为什么我的shell脚本在第二次尝试时失败?

Bash 为什么我的shell脚本在第二次尝试时失败?,bash,darwin,getopts,Bash,Darwin,Getopts,这个脚本应该接受一组搜索词并返回一个格式化的URL来搜索google $ ./google_search.sh albert einstein https://www.google.com/search?q=albert+einstein 它做得很好,所以我决定添加一个选项来搜索特定站点,或者使用-s或-s标志忽略该站点 $ ./google_search.sh -s wikipedia.org albert einstein https://www.google.com/search?q=a

这个脚本应该接受一组搜索词并返回一个格式化的URL来搜索google

$ ./google_search.sh albert einstein
https://www.google.com/search?q=albert+einstein
它做得很好,所以我决定添加一个选项来搜索特定站点,或者使用
-s
-s
标志忽略该站点

$ ./google_search.sh -s wikipedia.org albert einstein
https://www.google.com/search?q=albert+einstein+site%3Awikipedia.org
这在您第一次运行脚本时起作用,但在接下来的每次尝试中都失败

$ ./google_search.sh -s wikipedia.org albert einstein
https://www.google.com/search?q=albert+einstein
$ ./google_search.sh -s wikipedia.org albert einstein
https://www.google.com/search?q=albert+einstein
打开新的终端窗口或重新启动终端都会清除此问题,并允许在失败之前再次尝试

剧本:

#!/bin/bash

# original source of concatenate_args function by Tyilo:
# http://stackoverflow.com/questions/9354847/concatenate-inputs-in-bash-script
function concatenate_args
{
    string=""
    ignorenext=0
    for a in "$@" # Loop over arguments
    do
        if [[ "${a:0:1}" != "-" && $ignorenext = 0 ]] # Ignore flags (first character is -)
        then
            if [[ "$string" != "" ]]
            then
                string+="+" # Delimeter
            fi
            string+="$a"
        elif [[ $ignorenext = 1 ]]
        then
            ignorenext=0
        else
            ignorenext=1
        fi
    done
    echo "$string"
}

qry="$(concatenate_args "$@")"
glink="https://www.google.com/search?q="

site=""
while getopts :s:S: opt; do
    case $opt in
        s) site="+site%3A$OPTARG" ;; 
        S) site="+-site%3A$OPTARG" ;; 
    esac
done

url=$glink$qry$site

echo $url
# open -a Firefox $url

需要进行哪些更改才能使此脚本更可靠?

这就像是您正在寻找脚本的来源,而不是执行脚本。如果在脚本之前使用点和空格,则会导致在当前shell中逐行执行脚本,而不是创建新的shell。这允许在脚本中更改的环境变量泄漏到当前shell的环境中,这会使脚本的一次运行与下一次运行的行为不同


在本例中,似乎是使用了getopts。每次调用环境变量时,getopts都会更新它,以便跟踪正在检查的参数。第二次编写脚本时,它认为所有参数都已检查过,因此您的参数最终被忽略。

您的脚本,简化:

#!/bin/bash
glink="https://www.google.com/search?q="
site=""

# if you're "source"ing, uncomment the following:
# OPTIND=1

while getopts :s:S: opt; do
    case $opt in
        s) site="+site:$OPTARG" ;; 
        S) site="+-site:$OPTARG" ;; 
        ?) echo "invalid option: -$OPTARG" >&2 ;;
    esac
done
shift $((OPTIND - 1))
# the positional parameters are now clear of "-s" and "-S" options

qry=$(IFS="+"; echo "$*")
url=$glink$qry$site
echo "$url"
# open -a Firefox "$url"

-xv
选项添加到shebang行以查看发生了什么。这似乎没有任何作用。我正在努力/bin/bash-xv。这就像是在寻找脚本的来源,而不是执行脚本。您确定使用的是
/google\u search.sh
而不是
。google_search.sh
?请尝试
bash google\u search.sh
。或者,您正在编辑脚本的另一个副本。如果脚本是可执行的,只需删除点并使用
别名google=/Tools/google\u search.sh
。如果没有,请使用
别名google='bash/Tools/google_search.sh'
您刚刚回答了我接下来要问的问题,“当脚本‘源代码’时会发生什么不同?”我将花大量时间学习如何使用它。再次感谢!