The reason is that you are not correctly quoting your input. The parameter you pass to the script contains $
, and you pass the parameter unquoted (i.e. simply as NS3#$xX$56M
), which means it will be subject to variable expansion. This means that the shell that interprets your
sh test.sh e NS3#$xX$56M
command to call the test.sh
script will first try to substitute the $xX
part with the content of a shell variable (either locally defined or exported as environment variable) xX
, and - since there likely isn't any - substitutes this part with "nothing", before it passes the result to your script. However, this is the correct functioning of the shell, and hence there is nothing principally wrong with your script (as noted by @roaima).
To prevent this problem, enclose the string in single-quotes which will disable any expansions:
sh test.sh e 'NS3#$xX$56M'
As a general note on your script:
- Don't use all-uppercase variable names unless you plan to export them to the environment (i.e. use
test
instead of TEST
) - this prevents unwanted clashes between variables of your script and possibly essential environment variables.
- Use
shellcheck
, also available as standalone program on many linux distributions, to "proof-read" your scripts; this will help prevent many errors.
- As you saw from the problem you encountered, always be sure to correctly quote shell variables when using them, unless you positively know that you want variable/glob expansion and word splitting to happen. This also applies to the usage of shell variables in your script.
- You call the script as
sh test.sh ....
This will override the #!
-line and use the sh
shell, which on many systems will be a POSIX-compliant shell that doesn't understand the [[ ... ]]
operator e.g. Either make it executable and call it as ./test.sh
, or explicitly use bash test.sh
.