Home > Mobile >  Can I pass a literal $ into a bash script from the command line?
Can I pass a literal $ into a bash script from the command line?

Time:05-07

I'm creating a bash script and I need to be able to accept a string as the first parameter. This string may contain the $ character.

Script
#/bin/bash
pass="$1"
echo $pass
Output
root@server:/home# ./test.sh abc$xyz
abc

As you can see, the $ in the input is causing a problem because it's trying to interpret it as $xyz instead of a literal. Returning abc$xyz would be considered a successful response.

CodePudding user response:

When you invoke:

$ ./test.sh abc$xyz

the shell parses that line by first looking for a variable named xyz. If that variable is unset, then $xyz expands to the null string and ./test.sh abc$xyz becomes ./test.sh abc. If you want to pass the literal string abc$xyz to your script, you should quote it to prevent the shell from doing any interpolation:

$ ./test.sh 'abc$xyz'

On an unrelated note, don't use the .sh suffix on your scripts. (https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/). But in this case, you shouldn't just remove the suffix, since test is also a terrible name for a script.

CodePudding user response:

Enclose in single quotes characters or sections of the string to prevent the shell from interpreting them.

Alternatively, escape some special characters that are normally interpreted. Echo below shows what would be passed to a script:

echo Hi'\'myFriend     =>  Hi\myFriend
echo Hi\$myFriend      =>  Hi$myFriend
echo Hi\"myFriend\"    =>  Hi"myFriend"
echo 'Hi "$myFriend"'  =>  Hi "$myFriend"
echo "Hi $myFriend"    =>  Hi
  • Related