简体   繁体   中英

How to preserve doubles quoted arguments passed to a bash script?

I am trying to run a.sh file by passing few arguments. The file contains the following.

# escape special characters
ESCAPED_REPLACE=$(printf '%s ' "$@" | sed -e 's/[$()"]/\\&/g')

echo "After replace"
echo $ESCAPED_REPLACE

npx codeceptjs "$ESCAPED_REPLACE" --plugins allure

Following is a sample list of arguments. As it shows the last argument contains double quotes. Which I need to preserve here

./test.sh run --steps --grep "Verifying login"

The issue is once I print the ESCAPED_REPLACE the quotes are lost. Does anyone know why?

Quotes that are passed to your script are printed correctly. However, in your example ./test.sh run --steps --grep "Verifying login" you don't pass any quotes to the script, since bash interprets them before test.sh even runs.

To pass quotes to your script, you have to escape them:

./test.sh run --steps --grep "\"Verifying login\""

Anyways, I'm not sure you really need sed -e 's/[$()"]/\\&/g' . To me this seems like a misunderstanding of how bash interprets special symbols. When you write "$variable" the special symbols inside variable are not interpreted. Therefore, you normally don't have to quote the content of variable . I'd assume the following to work:

Content of test.sh

#! /bin/sh
npx codeceptjs "$@" --plugins allure

Execution

./test.sh run --steps --grep "Verifying login"

Can you do something like:

#!/bin/bash
# file name: test

echo "K: ${@@K}"

echo "find ${@@K}"
eval "find ${@@K}"

This should pass everything to find just as if you typed it directly

$ ./test ../Downloads -name "This is a test.pdf"
K: '../Downloads' '-name' 'This is a test.pdf'
find '../Downloads' '-name' 'This is a test.pdf'
../Downloads/This is a test.pdf

If I am reading your question right, that is what you are trying to do. Special characters will be interpreted in the shell before passing them to your script unless you escape them first:

$./test \$var1 "\$var2 \$var3" '$var4 single quotes work too'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM