1

How can I store the url-decoded string in a variable using shell script

#!/bin/sh
alias urldecode='python -c "import sys, urllib as ul;print ul.unquote_plus(sys.argv[1])"'
str="this+is+%2F+%2B+%2C+.+url+%23%24coded"

decoded = ${urldecode $str}
echo $decoded

I am trying to store decoded string in variable named decoded.

4
#!/bin/sh -
urldecode() {
  python -c "import sys, urllib as ul;print ul.unquote_plus(sys.argv[1])" "$1"
}
str="this+is+%2F+%2B+%2C+.+url+%23%24coded"
decoded=$(urldecode "$str"}
printf '%s\n' "$decoded"

That is:

  • avoid aliases in scripts as that's not guaranteed to work (some sh implementations like bash ignore aliases when non-interactive)
  • quote your variables. Leaving a variable unquoted is the split+glob operator in shells.
  • The operator to substitute the output of a command is $(...)
  • variable assignment syntax in Bourne-like shells doesn't allow blanks around =, echo = x means calling the echo command with = and x as arguments, not assigning x to the echo variable.
  • You can't use echo to display arbitrary data, use printf instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.