修改传递给脚本的参数 (Bash) [英] Modifying a parameter pass to a script (Bash)
问题描述
我已经在 Google 上搜索了很长时间,但找不到与我需要/想做的事情相匹配的任何内容.
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
list = /bin/foo:/bin/random:random
添加到列表:/bin/foobar
to add to list: /bin/foobar
调用脚本会产生/bin/foo:/bin/random:random:/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
然而这产生了错误.它说没有找到该命令,并给了我 $1="$NEWLIST" 所在的行号.我在这里做错了什么?我如何修改 $1?谢谢!
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? How do I modify $1? Thanks!
$ 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.
推荐答案
adymitruk 已经说过了,但是为什么要赋值给一个参数.这样做不行吗?
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
也许是这样:
list="1:2:3:4"
list=`./script $list 5`;echo $list
大
使用此脚本(例如称为 listadd):
Use this script (called listadd for instance):
if ! `echo :${!1}: | grep ":$2:" 1>/dev/null 2>&1`
then
export $1=${!1}:$2
fi
并从您的 shell 中获取它.结果如下(我希望这是 wsa 的意图):
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
这篇关于修改传递给脚本的参数 (Bash)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!