Haishan
Haishan

Reputation: 43

How to handle quoted arguments in $@?

For example here is test.sh

#!/bin/bash

for i in "${@}"; do
    echo "${i}"
done

If you run ./test.sh one 'two' "three", you will get

one
two
three

But what I want to get is:

one
'two'
"three"

How can I get this?

Thanks.

Upvotes: 2

Views: 64

Answers (2)

vlp
vlp

Reputation: 603

you need to adapt your input. For example like this:

# ./test.sh one \'two\' \"three\"
one
'two'
"three"
#

Upvotes: 2

patapouf_ai
patapouf_ai

Reputation: 18693

Bash strips the quotes from strings. Thus if you want quotes, you need to put them inside other quotes.

Doing:

./test.sh one "'two'" '"three"'

should give you the result you want.

Another possibility is to escape your quotes so that bash knows that it is part of the string:

./test.sh one \'two\' \"three\"

will work, so will:

./test.sh "one" "\'two\'" "\"three\""

Otherwise you can always add the quotes again in your script by doing:

echo "\"${i}\""

for example.

Upvotes: 2

Related Questions