-1

This is a simplified version of a script that runs with one parameter

#!/bin/bash
K1=eval /usr/bin/urlencode "$1" 
echo "$K1" # prints the correct url encoded $1 parameter
echo "$K1" # nothing printed

I looked at other more complex questions/answers to get why the variable lose its content

Moreover, without echoing $K1 anytime, I lose its value if I try to use it in another value like K2="zgrep $K1$DIR. Echoing $K2 prints zgrep $DIR value

  • 2
    cut-n-paste your code (along with shebang) into [shellcheck.net](https://www.shellcheck.net/) and make the recommend change (ie, there's a problem with your `K1=eval ...` line) – markp-fuso Aug 19 '23 at 16:52
  • `K1=$(eval /usr/bin/urlencode "$1")` is the correct way to assign the result to `K1`. – Daniel Franco Aug 19 '23 at 18:10
  • `eval` is likely not required, ie, `K1=$(/usr/bin/urlencode "$1")` should be sufficient – markp-fuso Aug 19 '23 at 18:22

1 Answers1

1

As running this with bash -x will readily reveal, the echo outputs the variable's value both times. You are assigning K1="eval" for the duration of the urelencode command, and its results are simply being displayed on standard output. Presumably K1 was unset, so it then returns to an empty string; you are then running echo "" twice.

I'm guessing you were trying to say

k1=$(urlencode "$1")
echo "$k1"
echo "$k1"

This is a very common beginner problem. See also How do I set a variable to the output of a command in Bash?, Assignment of variables with space after the (=) sign?, and somewhat more tangentially Correct Bash and shell script variable capitalization

/usr/bin should already be on your PATH so I can't see a good reason to provide a full path to the executable. If you genuinely have a different tool with the same name earlier on your PATH, probably sort out that problem instead.

tripleee
  • 175,061
  • 34
  • 275
  • 318