0

I'm a bash noob and can't figure out how to use a string containing spaces in a bash argument. Here's the function giving me problems...

handle_arguments() {

ARGUMENTS=($@);

for i in ${ARGUMENTS[@]}
    do

        INDEX=`expr index "$i" =`;

        case $i in
            --projectslug*)
                PROJECT_SLUG=${i:INDEX};
            ;;
            --sitename*)
                SITE_NAME=${i:INDEX};
            ;;
            --build*)
                BUILD_TYPE=${i:INDEX};
            ;;
            --dbname*)
                DB_NAME=${i:INDEX};
            ;;
            --mysqlun*)
                MYSQL_UN=${i:INDEX};
            ;;
            --mysqlpw*)
                MYSQL_PW=${i:INDEX};
            ;;
            --dbfilename*)
                DB_FILE_NAME=${i:INDEX};
            ;;
            --search*)
                DB_SR_SEARCH=${i:INDEX};
            ;;
            --replace*)
                DB_SR_REPLACE=${i:INDEX};
            ;;
            *)
                echo -e "${RED}$i is not recognized as an argument.${NC}\n";
            ;;
        esac
done;

if [[ -z $DB_NAME ]];
    then
        DB_NAME=$PROJECT_SLUG;
fi
}

The command I run is...

$ source wpautobuild.sh; wp_auto_build --projectslug=abctest1 --sitename="ABC TEST 1"

I've been troubleshooting this for hours and everything I'm finding is telling me to wrap $@ in ARGUMENTS=($@); with double quotes so it's ARGUMENTS=("$@"); but that does not work.

I've also tried adding double quotes to SITE_NAME=${i:INDEX}; to be SITE_NAME="${i:INDEX}"; but also with no luck.

One article suggested escaping spaces in the command like this...

$ source wpautobuild.sh; wp_auto_build --projectslug=abctest1 --sitename="ABC\ TEST\ 1"

...and that did not work either.

Note: The handle_arguments() function is run in the wp_auto_build() function which is being called in the command.

I'm totally stuck and appreciate any help I can get. Thanks in advance.

markp-fuso
  • 28,790
  • 4
  • 16
  • 36
CChoma
  • 1,076
  • 1
  • 9
  • 25

1 Answers1

2

You need to quote $@ for it to preserve spaces. Unquoted $@ serves no purpose, as it is identical to unquoted $*.

ARGUMENTS=("$@")

You subsequently need to quote ${ARGUMENTS[@]} for the same reason

for i in "${ARGUMENTS[@]}"

though there is no need for ARGUMENTS at all; you can iterate over "$@" directly.

for i in "$@"
chepner
  • 497,756
  • 71
  • 530
  • 681
  • Got it working now. There was just one more place in the other function where called the wp_auto_build() function that I also needed to quote `handle_arguments "$@";'. Thanks for the help! – CChoma Dec 02 '20 at 18:51