bashfunctionpass-by-referenceurldecode

HOW can I call a function in a bash file script?


I would like to urldecode a whole file, because there are a few %20 and other ASCII-Numbers in it. I tried this but I do not know how I can call the function defined above in the script in the main routine.

    #!/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"                
    

Solution

  • The format of the program is correct. But you have called your functions not in a correct way.

    This is correct way of calling your function in your loop:

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

    To get the inputs for the function you need to use $1, $2, $3, etc. This is already implemented in your code. As a sample:

    # define the function
    myfunction() {
      echo "$1";
      echo "$2";
      echo "$3";
    }
    
    # call the function
    myfunction "First Input" "Second Input" "Third Input"