Modifying a parameter pass to a script (Bash)

前端 未结 3 532
醉酒成梦
醉酒成梦 2021-01-12 13:41

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 tw

相关标签:
3条回答
  • 2021-01-12 14:25

    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
    
    0 讨论(0)
  • 2021-01-12 14:41

    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
    
    0 讨论(0)
  • 2021-01-12 14:42

    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 讨论(0)
提交回复
热议问题