Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

manipulate parameters in sh

I'm working with a utility (unison, but that's not the point) that accepts parameters like:

$ unison -path path1 -path path2 -path path3

I would like to write a sh script that I could run like this:

$ myscript path1 path2 path3

I'm hoping for a Posix compliant solution, but bash-specific would also be good.

I'm guessing it should be something like:

#!/bin/sh
unison ${*/ / -path }

But this doesn't work.

EDIT: OK, I think I got something:

#!/bin/bash
PARAMS=
for arg in "$@"
do
    PARAMS+=" -path '$arg'"
done
unison $PARAMS

The problems are this only works in bash, and I'm pretty sure there's a better way to quote the parameters.

like image 708
itsadok Avatar asked Dec 10 '22 20:12

itsadok


1 Answers

Unchecked, it could be as simple as:

exec unison -path $1 -path $2 -path $3

If you don't embed spaces in your path names, then you can deal with a variable number of arguments with:

arglist=""
for path in "$@"
do
    arglist="$arglist -path $path"
done
exec unison $arglist

If you have spaces in your path names, then you have to work a lot harder; I usually use a custom program called escape, which quotes arguments that need quoting, and eval:

arglist=""
for path in "$@"
do
    path=$(escape "$path")
    arglist="$arglist -path $path"
done
eval exec unison "$arglist"

I note that using Perl or Python would make handling arguments with spaces in them easier - but the question asks about shell.

It might also be feasible in Bash to use a shell array variable - build up the arguments into an array and pass the array as the arguments to the unison command.

like image 83
Jonathan Leffler Avatar answered Dec 30 '22 20:12

Jonathan Leffler