jesse_galley
jesse_galley

Reputation: 1676

reading strings containing backslashes into variables in bash

Okay, So I have a CSV file of users and passwords, the passwords sometimes contain backslashes, I need to loop over this file and pass the user and password to another script, but I can't figure out how to make bash take the backslash as a literal character.

The csv:

jgalley@debian1mig:~/logs/zimbraShares$ cat test.csv 
[email protected],bzfbx6bkuu\Mpull
[email protected],Hppk8mll\kffbsfd
[email protected],w1fgfqbjlhLjnni\

Sed is not expanding the backslashes - this is good:

jgalley@debian1mig:~/logs/zimbraShares$ cat test.csv | sed "s/,/\t/" 
[email protected]        bzfbx6bkuu\Mpull
[email protected]        Hppk8mll\kffbsfd
[email protected]        w1fgfqbjlhLjnni\

trying to read them into variables causes the backslash to be a meta-character, as you can see, it escapes the characters and also causes the last line to escape the return character since it's on the end:

jgalley@debian1mig:~/logs/zimbraShares$ cat test.csv | sed "s/,/\t/" | while read user pass; do echo "${user},${pass}"; done
[email protected],bzfbx6bkuuMpull
[email protected],Hppk8mllkffbsfd

Trying to escape the backslashes first also doesn't work:

jgalley@debian1mig:~/logs/zimbraShares$ cat test.csv | sed "s/,/\t/" | sed "s/\\\/\\\\/g" | while read user pass; do echo "${user},${pass}"; done
[email protected],bzfbx6bkuuMpull
[email protected],Hppk8mllkffbsfd
jgalley@hoth1mig:~/logs/zimbraShares$ 

The ultimate goal will be do something like this:

head test.csv | sed "s/,/\t/g" | while read auser apass;
do 
  echo -n "${auser},${apass}"
  bash -c  "/home/jgalley/scripts/someScript.php -u '${auser}' -p '${apass}' -d '${auser}'";      
done

Upvotes: 4

Views: 1741

Answers (1)

P.P
P.P

Reputation: 121407

Use the -r option of read:

while read -r auser apass;

If -r is given, the \ won't be considered as an escape character.

Upvotes: 7

Related Questions