1

I have a Bash script which (in a simplified form) does this:

#!/bin/bash

function ag_search_and_replace {
  ag -l "$1" "${@:3}" | xargs -r perl -i -pe "s/$1/$2/g"
}

locations="$@"

ag_search_and_replace search replace $locations

This works as expected when the argument have no spaces, e.g.:

my_script foo bar

however, when there are spaces, e.g.:

my_script foo "ba r"

the script fails.

Is there a simple way to process arguments with spaces?

1 Answer 1

4

"$@" is the way to do it, but you lose the benefits when you unnecessarily assign it to a regular variable.

ag_search_and_replace search replace "$@"

If you must create a new named variable, use an array.

locations=( "$@" )
ag_search_and_replace search replace "${locations[@]}"
Sign up to request clarification or add additional context in comments.

4 Comments

The assignment to regular variable is necessary in the context of the full script :-) This is a simplified version; I've put the assignment for consistency with the script.
Then the full script is broken.
What do you refer, specifically, with broken (I assume it's something else other than what you corrected by the reply)?
Because location="$@" and location="$*" do exactly the same thing, and neither one lets you retrieve the original arguments from location. If location='a b c', then did you originally have 1) a b c, 2) a b and c, 3) a and b c, or 4) a, b, and c?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.