为什么除了第一个参数之外的所有参数都被忽略?

Why do all arguments except the first one get ignored?

我正在尝试制作自定义命令提示符。例如,如果我输入

. filename.sh 1 hello 2 hi 3 a 0 b

自定义提示应如下所示:

[b][hello][hi][a]$

数字 1 代表第二个位置,数字 2 代表第三个位置等。但是当我 运行 它时,不知何故只显示第一部分,如下所示:

[][hello][][]$

而且我无法覆盖它。例如,当我输入

. filename.sh 2 hi

它应该是 [][hello][hi][]$ 但它变成了 [][][hi][]$。我该如何解决?

#!/bin/bash

# []  []  []  []

PS1="[][][][]$"

for i in "$*"
do

    #
    if [  -eq 0 ]
    then
        PS1="[][][][]$"
    elif [  -eq 1 ]
    then
        PS1="[][][][]$"
    elif [  -eq 2 ]
    then
        PS1="[][][][]$"
    elif [  -eq 3 ]
    then
        PS1="[][][][]$"


        #
    elif [  -eq 0 ]
    then
        PS1="[][][][]$"
    elif [  -eq 1 ]
    then
        PS1="[][][][]$"
    elif [  -eq 2 ]
    then
        PS1="[][][][]$"
    elif [  -eq 3 ]
    then
        PS1="[][][][]$"


        #5
    elif [  -eq 0 ]
    then
        PS1="[][][][]$"
    elif [  -eq 1 ]
    then
        PS1="[][][][]$"
    elif [  -eq 2 ]
    then
        PS1="[][][][]$"
    elif [  -eq 3 ]
    then
        PS1="[][][][]$"

        #7
    elif [  -eq 0 ]
    then
        PS1="[][][][]$"
    elif [  -eq 1 ]
    then
        PS1="[][][][]$"
    elif [  -eq 2 ]
    then
        PS1="[][][][]$"
    elif [  -eq 3 ]
    then
        PS1="[][][][]$"
    fi

done

不要将参数视为一个单词。一次迭代两个参数。

# You can do something simpler with an array, but I'm deliberately keeping
# this POSIX-compatible.
while [ "$#" -gt 0 ]; do
    pos=

    case $pos in
      0) v0= ;;
      1) v1= ;;
      2) v2= ;;
      3) v3= ;;
      *) printf 'Illegal slot %d' "$pos" >&2; exit 1 ;;
    esac
    shift
    shift
done

PS1="[$v0][$v1][$v2][$v3]"

如果你做for i in "$*"i的值是字符串1 hello 2 hi 3 a 0 b,所以循环只执行一次。

即使您确保您的循环不止一次得到 运行,您仍然会得到一个提示,其中只设置了一个字段; PS1 的所有赋值只设置一个字段。

你必须动态构建它,例如像这样:

# Make sure PS1 is empty
unset PS1

# As long as we see command line parameters
while (($#)); do
    # Set array element at index of first parameter to value of second parameter
    arr[]=

    # Drop current parameters
    shift 2
done

# Iterate over array and build PS1
for i in {0..3}; do
    PS1+="[${arr[i]}]"
done

# Unset array so it doesn't stick around in environment
unset arr

PS1+='$'

正在使用:

$ . prompt.bash 1 hello 2 hi 3 a 0 b
[b][hello][hi][a]$

或者只提供一个元素:

$ . prompt.bash 3 X
[][][][X]$