jBee
jBee

Reputation: 193

How to detect arguments with single or double quotes?

In shell (restricted Ksh):

script1.sh "arg1 arg" arg2 'agr3 arg4' ...

(the number of arguments and order with quoted args is random)

How to detect in script whether we used single or double quotes in arg list?

Upd: next code not find quotes if one quoted args:

if [[ "$#" == *"\""* ]]; then echo "Quotes not accepted" >&2 exit 1 fi

Upvotes: 1

Views: 196

Answers (1)

codeforester
codeforester

Reputation: 43039

The quotes are interpreted by the shell before the command (your script script1.sh in this case) is invoked. I am not sure why your script wants to know if arguments were quoted. To achieve your goal, you need to put your arguments in two sets of quotes - use double quotes to protect single quotes and single quotes to protect double quotes, like this:

script1.sh '"arg1 arg"' arg2 "'arg3 arg4'" ...

In this case, the script would see:

$1 => "arg1 arg"  # double quotes are a part of the string
$2 => arg2
$3 => 'arg3 arg4' # single quotes are a part of the string

Then the script can check for quotes:

[[ "$1" = \"*\" ]] && echo "argument 1 has double quotes"
[[ "$3" = \'*\' ]] && echo "argument 3 has single quotes"

See also:

Upvotes: 2

Related Questions