Home > Software design >  bash script command line passing double quotas does not work
bash script command line passing double quotas does not work

Time:01-24

this is my bash script, test.sh

#!/bin/bash

printf '1st printf:\n%s\n\n\n' 'find . -name "*.[ch]"'${1}

printf '2nd printf:\n%s\n' 'find . -name "*.[ch]"'" ${1}"

find . -name "*.[ch]"  ${1}

I run it as test.sh "-not -path \"*examples*\"" and here is the output:

1st printf:
find . -name "*.[ch]"-not


1st printf:
-path


1st printf:
"*examples*"


2nd printf:
find . -name "*.[ch]" -not -path "*examples*"

what I try to is to run find . -name "*.[ch]" -not -path "*examples*" inside the script. But the $1 is treated like a list or something? How do I construct the right command line inside the script?

CodePudding user response:

Use single quotes for static strings and double quotes for variables.

find . -name '*.[ch]' -not -path "$1"

Note: Escape *, to stop the shell from expanding it. Run your script this way:

./myscript '*examples*'

Or this way:

./myscript \*examples\*

CodePudding user response:

Don't put quotes (or escapes) in your data (i.e. parameters, variables, etc). Quotes go around data, not in data. If you want to pass multiple parameters to add to a find command, pass each one as a separate parameter (just as you would to find itself), and use "$@" to expand them (double-quotes required to avoid parsing weirdness).

#!/bin/bash
find . -name "*.[ch]" "$@"

Then run it as test.sh -not -path "*examples*"

  •  Tags:  
  • Related