0

I want to put this string into a variable without having to worry about escaping anything within it.

j!'^+%&/()=1!'^+%&/()c

TRY 1: ( failed )

VAR='''j!'^+%&/()=1!'^+%&/()c'''
bash: !'^+%: event not found

what should I do ?

5

From this answer:

$ IFS='' read -r -d '' var <<'EOF'
j!'^+%&/()=1!'^+%&/()c
EOF
$ echo "$var"
j!'^+%&/()=1!'^+%&/()c
$

Or, accept the input via a different program than the shell using cat:

$ var=$(cat)
j!'^+%&/()=1!'^+%&/()c        
$ echo "$var"
j!'^+%&/()=1!'^+%&/()c
$

After your input, press Enter then Ctrl+D.

Or, using bash's printf:

$ xargs -0 printf "\n%q\n"
j!'^+%&/()=1!'^+%&/()c
'j!'\''^+%&/()=1!'\''^+%&/()c'
$ var='j!'\''^+%&/()=1!'\''^+%&/()c'
$ echo "$var"
j!'^+%&/()=1!'^+%&/()c
$

Here, you'll need to not press Enter, but press Ctrl+D twice after entering the text to be quoted.

2

I do a lot of this and have settled on just always enclosing the whole string in double quotes and escaping any double-quotes (\") or dollar signs (\$). This is easier to remember than anything else.

Another, often overlooked, technique is to concatenate adjacent strings inside different quotes.

VAR=" string without double-quotes "' string with "double-quotes" '

Here, I included extra spaces just so the quotes stand out. The double-quote followed by a single-quote in the center cannot have space or anything between them. They are at the end of the first string and beginning of the second string respectively. Being adjacent concatenates the two strings.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy