I'm creating a bash script to write variable values to a csv file. But unable to write particular values that contain " and ' symbols in the line. For example, I have variables and values like this available into the shell:
username: my-name@abc.com
name: my-name
password: j50z54"#7b'y'/3l7H%7
If try to write them to a csv file like this:
echo -e "username,password,name" >> abc.csv
echo -e "$username,$password,$name" >> abc.csv
I get an error:
line 2: unexpected EOF while looking for matching `"'
line 3: syntax error: unexpected end of file
Thre problem occurs due to the presence of double quotes and single quotes in the value.
Method 1:
Store the variable value as follows:
- escape all double quotes and single quotes by prepending them with a backslash \
- enclose the entire variable value within double quotes.
For example, an actual value of password j50z54"#7b'y'/3l7H%7
should be saved as "j50z54\"#7b\'y\'/3l7H%7"
Then if I run the following script:
echo -e "username,password,name" >> abc.csv
echo -e "$username,$password,$name" >> abc.csv
sed -i 's/\\//g' abc.csv
I get the proper csv file:
username,password,name
my-name@abc.com,j50z54"#7b'y'/3l7H%7,my-name
BUT, the problem is that it is not possible to modify the variable value ( at its source ) as in the above-mentioned format.
Method 2:
I tried a metho as shown here, the script:
username=my-name@abc.com
name=my-name
cat >> abc.csv << \EOF
Username,Password,Name
$username,j70z38"#7k'y'/3l7H%9,$name
EOF
gives output file abc.csv:
Username,Password,Name
$username,j70z38"#7k'y'/3l7H%9,$name
(please ignore the fact that password value is directly provided here for just testing purposes)
In this method, variable names like $username and $name are printed instead of their values.
Question:
Is there any other better way/script to write the variable value properly to a CSV file?
ADDITIONAL INFORMATION:
This script is used for automation inside a bash task of the Azure DevOps pipeline. Also, the password is saved in a variable group there and is available inside the pipeline as $(password)
.