Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

#!/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.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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