开发者

Modifying a parameter pass to a script (Bash)

I have been looking on Google for quite a while now and can't find anything that is matching what I need/want to do.

My objective is to write a script that takes two arguments. It will search through the first argument (which is a list) and detect if the second argument is already in it. For example:

list = /bin/foo:/bin/random:random

to add to list: /bin/foobar

Calling the script will produce the result of /bin/foo:/bin/random:random:/bin/foobar.

If the part to add to the list is already in the list then nothing will be changed of the original.

I have everything working up until the point where I want to modify the parameter I passed.

...
if [ $RUN = 1 ]; then
    echo $1
else
    $1="$NEWLIST"
fi
exit 0

This however produced an error. It says that the command isn't found and gives me the line number that $1="$NEWLIST" is on. What am I doing wrong here? Ho开发者_运维知识库w do I modify $1? Thanks!

edit:

$ PATH=/opt/bin:$PATH
$ ./scrip.sh PATH /user/opt/bin
$ /opt/bin:/user/opt/bin

This is what I would want as a result of the script.


To set the positional parameters $1, $2, ..., use the set command:

set foo bar baz
echo "$*"   # ==> foo bar baz
echo $1     # ==> foo

set abc def
echo "$*"   # ==> abc def

If you want to modify one positional parameter without losing the others, first store them in an array:

set foo bar baz
args=( "$@" )
args[1]="BAR"
set "${args[@]}"
echo "$*"   # ==> foo BAR baz


adymitruk already said it, but why do you want to assign to a parameter. Woudln't this do the trick?

if `echo :$1: | grep ":$2:" 1>/dev/null 2>&1`
then
  echo $1
else
  echo $1:$2
fi

Maybe this:

list="1:2:3:4"
list=`./script $list 5`;echo $list

BIG EDIT:

Use this script (called listadd for instance):

if ! `echo :${!1}: | grep ":$2:" 1>/dev/null 2>&1`
then
  export $1=${!1}:$2
fi

And source it from your shell. Result is the following (I hope this is what wsa intended):

lorenzo@enzo:~$ list=1:2:3:4
lorenzo@enzo:~$ source listadd list 3
lorenzo@enzo:~$ echo $list
1:2:3:4
lorenzo@enzo:~$ source listadd list 5
lorenzo@enzo:~$ echo $list
1:2:3:4:5
lorenzo@enzo:~$ list2=a:b:c
lorenzo@enzo:~$ source listadd list2 a
lorenzo@enzo:~$ echo $list2
a:b:c
lorenzo@enzo:~$ source listadd list2 d
lorenzo@enzo:~$ echo $list2
a:b:c:d


First copy your parameters to local variables:

Arg1=$1

Then, where you are assigning leave off the $ on the variable name to the left of the =

You can't have a $ on the left hand side of an assignment. If you do, it's interpreting the contents of $1 as a command to run

hope this helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜