如何在 bash 文件脚本中调用函数?

问题描述

我想对整个文件进行 urldecode,因为其中有一些 %20 和其他 ASCII 数字。 我试过了,但我不知道如何在主例程的脚本中调用上面定义的函数

    #!/bin/bash                
    urlencode() {                
        # urlencode <string>                
                    
        old_lc_collate=$LC_COLLATE                
        LC_COLLATE=C                
                    
        local length="${#1}"                
        for (( i = 0; i < length; i++ )); do                
            local c="${1:$i:1}"                
            case $c in                
                [a-zA-Z0-9.~_-]) printf '%s' "$c" ;;                
                *) printf '%%%02X' "'$c" ;;                
            esac                
        done                
                    
        LC_COLLATE=$old_lc_collate                
    }                
                    
    urldecode() {                
        # urldecode <string>                
                    
        local url_encoded="${1//+/ }"                
        printf '%b' "${url_encoded//%/\\x}"                
    }                
                    
    while IFS= read -r line; do                
        echo urldecode($line)                
    done < "$1"                
    

解决方法

程序格式正确。但是您调用函数的方式不正确。

这是在循环中调用函数的正确方法:

# define the function
myfunction() {
  echo "$1";
  echo "$2";
  echo "$3";
}

# call the function
myfunction "First Input" "Second Input" "Third Input"

要获取函数的输入,您需要使用 $1、$2、$3 等。 这已经在您的代码中实现了。 作为示例:

Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Filter.getRange.
CollectCases    
,

您可以在一个脚本中分离功能:

    #!/bin/bash                
urlencode() {                
    # urlencode <string>                
                
    old_lc_collate=$LC_COLLATE                
    LC_COLLATE=C                
                
    local length="${#1}"                
    for (( i = 0; i < length; i++ )); do                
        local c="${1:$i:1}"                
        case $c in                
            [a-zA-Z0-9.~_-]) printf '%s' "$c" ;;                
            *) printf '%%%02X' "'$c" ;;                
        esac                
    done                
                
    LC_COLLATE=$old_lc_collate                
}                
                
urldecode() {                
    # urldecode <string>                
                
    local url_encoded="${1//+/ }"                
    printf '%b' "${url_encoded//%/\\x}"                
} 

然后通过添加 source 命令和带有声明函数的脚本以您想要的方式在其他脚本中执行此函数:

source script.sh

while IFS= read -r line; do                
    echo urldecode($line)                
done < "$1"