Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add prefix and suffix to $@ in bash

Tags:

bash

How to add suffix and prefix to $@?

If I do $PREFIX/$@/$SUFFIX, I get the prefix and the suffix only in the first parameter.

like image 621
Richard Avatar asked Jul 25 '16 01:07

Richard


People also ask

What does $@ do in bash script?

bash [filename] runs the commands saved in a file. $@ refers to all of a shell script's command-line arguments. $1 , $2 , etc., refer to the first command-line argument, the second command-line argument, etc. Place variables in quotes if the values might have spaces in them.

What is $@ and $* in shell script?

• $* - It stores complete set of positional parameter in a single string. • $@ - Quoted string treated as separate arguments. • $? - exit status of command.

Is $@ Same as $* in Linux?

$* Stores all the arguments that were entered on the command line ($1 $2 ...). "$@" Stores all the arguments that were entered on the command line, individually quoted ("$1" "$2" ...). Save this answer.

What's do `` $() ${} commands do in Bash?

Save this answer. Show activity on this post. $() means: "first evaluate this, and then evaluate the rest of the line". On the other hand ${} expands a variable.


2 Answers

I would use shell [ parameter expansion ] for this

$ set -- one two three
$ echo "$@"
one two three
$ set -- "${@/#/pre}" && set -- "${@/%/post}"
$ echo "$@"
preonepost pretwopost prethreepost

Notes

  • The # matches the beginning
  • The % matches the end
  • Using double quotes around ${@} considers each element as a separate word. so replacement happens for every positional parameter
like image 91
sjsam Avatar answered Oct 11 '22 00:10

sjsam


Let's create a parameters for test purposes:

$ set -- one two three
$ echo "$@"
one two three

Now, let's use bash to add prefixes and suffixes:

$ IFS=$'\n' a=($(printf "pre/%s/post\n" "$@"))
$ set -- "${a[@]}"
$ echo -- "$@"
pre/one/post pre/two/post pre/three/post

Limitations: (a) since this uses newline-separated strings, it won't work if your $@ contains newlines itself. In that case, there may be another choice for IFS that would suffice. (b) This is subject to globbing. If either of these is an issue, see the more general solution below.

On the other hand, if the positional parameters do not contain whitespace, then no change to IFS is needed.

Also, if IFS is changed, then one may want to save IFS beforehand and restore afterward.

More general solution

If we don't want to make any assumptions about whitespace, we can modify "$@" with a loop:

$ a=(); for p in "$@"; do a+=("pre/$p/post"); done
$ set -- "${a[@]}"
$ echo "$@"
pre/one/post pre/two/post pre/three/post
like image 40
John1024 Avatar answered Oct 11 '22 00:10

John1024