Hi,
I need to assign to a variable a value that has special characters in them, i.e. dollar, single quote, double quote, backticks etc that may have special meaning to the shell/OS.
At the moment, it appears like I have to either escape them, put the content of the variable value into a file and read from the file or use the read command to which I then enter the value of the variable.
Test script below:
$ cat test.bash
#!/bin/bash
#
x="123456"
echo $x
x="1!23456"
echo $x
x="1!\\23456"
echo $x
x="1!\\2%^&*()'3456"
echo $x
x="1!\\2%^&*(\`)'3456" # Need to escape the \`
echo $x
x="1!\\2%"^&\*()34$5$6" # Need to escape " and $
echo $x
echo "## TEST get the variable from a file instead. Contents of x1 is as below:"
cat x1
echo "## HERE is the variable with a backtick read from x1"
x=$( head -1 x1 )
echo $x
echo "## HERE is the variable with a dollar and quote read from x1"
x=$( tail -1 x1 )
echo $x
echo "## TEST USING read command to prompt for x for variable with a backtick"
read -p "Enter value for x -> " x
echo $x
echo "## TEST USING read command to prompt for x for variable with a dollar and quote"
read -p "Enter value for x -> " x
echo $x
Runtime of the script:
$ ./test.bash
123456
1!23456
1!\\23456
1!\\2%^&*()'3456
1!\\2%^&*(\`)'3456
1!\\2%"^&\*()34$5$6
## TEST get the variable from a file instead. Contents of x1 is as below:
1!\\2%^&*(\`)'3456
1!\\2%"^&*()34$5$6
## HERE is the variable with a backtick read from x1
1!\\2%^&\*(\`)'3456
## HERE is the variable with a dollar and quote read from x1
1!\\2%"^&\*()34$5$6
## TEST USING read command to prompt for x for variable with a backtick
Enter value for x -> 1!\\2%^&\*(`)'3456 1!2%^&*(`)'3456
## TEST USING read command to prompt for x for variable with a dollar and quote
Enter value for x -> 1!\\2%"^&*()34$5$6
1!2%"^&*()34$5$6
While using the option to read the value from a file or using read works fine, is there possibly a 100% fool proof way of assigning the value inside the script besides having to escape the character that needs escaping?