简体   繁体   中英

Assigning position variable in bash

How to assign a position variable in the if condition?

For example, my script name is test.sh . If I give the first variable as "T", I would like to see the printed variable $2 and $3. The primary reason is to use the $2 and $3 variable in other cases later. I would like to set the variable $2 and $3 10, and 15 respectively.

 #!/bin/bash

echo "The first variable : $1"
echo "The second variable  : $2"
echo "The third variable : $3"
if [ $1 == "T" ]
        then
         $2 = 10
         $5 = 15
fi
echo "$2"
echo "$3"

The error shows: "command not found". I guess I'm making a syntax error?

You can't assign to "position variables" (parameters). You can however use set, but you might lose the other parameters:

#!/bin/bash

echo "The first variable : $1"
echo "The second variable  : $2"
echo "The third variable : $3"
if [ "$1" == "T" ]
        then
        set -- T 10 15
fi
echo "$2"
echo "$3"

If you want to keep the other parameters, you will need to use "$@" and shift :

$ set -- 1 2 3 4 5 6 7 8 9 10
$ echo "$@"
1 2 3 4 5 6 7 8 9 10
$ set -- T 10 15
$ echo "$@"
T 10 15
$ set -- 1 2 3 4 5 6 7 8 9 10
$ shift 3
$ set -- T 10 15 "$@"
$ echo "$@"
T 10 15 4 5 6 7 8 9 10

if you are willing to forgo POSIX compatibility, you can also use ruakh suggestion in bash/zsh:

$ set -- 1 2 3 4 5 6 7 8 9 10
$ echo ${@:4}"
4 5 6 7 8 9 10
$ set -- T 10 15 "${@:4}"
$ echo "$@"
T 10 15 4 5 6 7 8 9 10

Note: "position variables" are actually shell parameters . Also, you clearly stated that you want to use them, but I have to tell you that most of the time you are better using normal shell variables.

Yes you have a syntax error. The way to assign to a variable is NAME=VALUE . Note no dollar sign, and no spaces around the equals sign. However, 2=VALUE is also not valid since a number is not a valid name. $2 is actually a parameter , not a variable.

You're not meant to assign to numbered parameters. You can do it using set -- , but the better method is to give them names as variables, eg

#!/bin/bash

first="$1"
second="$2"
third="$3"

echo "The first variable: $first"
echo "The second variable: $second"
echo "The third variable: $third"
if [ "$first" == "T" ]; then
    second=10
    third=15
fi
echo "$second"
echo "$third"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM