PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, July 5, 2022

[FIXED] HOW can I call a function in a bash file script?

 July 05, 2022     bash, function, pass-by-reference, urldecode     No comments   

Issue

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"


Answered By - Raham
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing