zsh vs bash:括号如何改变变量赋值行为?

时间:2016-05-02 16:41:15

标签: bash shell zsh

我在如何处理不同的现有shell中的变量赋值和括号方面遇到了一些麻烦和误解。

目前令我困惑的是以下内容:

始终使用以下命令

./script.sh a b c d

运行以下代码时

#!/bin/zsh

bar=$@

for foo in $bar
do
    echo $foo
done

输出

a b c d

#!/bin/zsh

bar=($@)

for foo in $bar
do
    echo $foo
done

它是(我最初想要的)

a
b
c
d

但是使用bash或sh

#!/bin/bash

bar=$@

for foo in $bar
do
    echo $foo
done

给出

a
b
c
d

#!/bin/bash

bar=($@)

for foo in $bar
do
    echo $foo
done

只是

a

那里发生了什么?

2 个答案:

答案 0 :(得分:3)

执行此操作时:

bar=($@)

你实际上是创建一个bash shell数组。要迭代 bash 数组,请使用:

bar=( "$@" ) # safer way to create array
for foo in "${bar[@]}"
do
    echo "$foo"
done

答案 1 :(得分:3)

联合行动

对于所涉及的两个shell,给出的示例将假定一个显式设置的argv列表:

# this sets $1 to "first entry", $2 to "second entry", etc
$ set -- "first entry" "second entry" "third entry"

在两个shell中,declare -p可用于以明确的形式发出变量名的值,但它们如何表示该表单可能会有所不同。

在bash中

bash中的扩展规则通常与ks​​h兼容,并且在适用的情况下与POSIX sh语义兼容。与这些shell兼容要求不带引号的扩展执行字符串拆分和glob扩展(例如,用当前目录中的文件列表替换*)。

在变量赋值中使用括号使其成为一个数组。比较这三个任务:

# this sets arr_str="first entry second entry third entry"
$ arr_str=$@
$ declare -p arr_str
declare -- arr="first entry second entry third entry"

# this sets arr=( first entry second entry third entry )
$ arr=( $@ )
declare -a arr='([0]="first" [1]="entry" [2]="second" [3]="entry" [4]="third" [5]="entry")'

# this sets arr=( "first entry" "second entry" "third entry" )
$ arr=( "$@" )
$ declare -p arr
declare -a arr='([0]="first entry" [1]="second entry" [2]="third entry")'

同样,在扩展时,引号和符号很重要:

# quoted expansion, first item only
$ printf '%s\n' "$arr"
first entry

# unquoted expansion, first item only: that item is string-split into two separate args
$ printf '%s\n' $arr
first
entry

# unquoted expansion, all items: each word expanded into its own argument
$ printf '%s\n' ${arr[@]}
first
entry
second
entry
third
entry

# quoted expansion, all items: original arguments all preserved
$ printf '%s\n' "${arr[@]}"
first entry
second entry
third entry

在zsh中

zsh在尝试做用户意味着什么,而不是与历史shell(ksh,POSIX sh等)的兼容方面做了大量的魔术。然而,即使在那里,做错事也可能产生你想要的结果:

# Assigning an array to a string still flattens it in zsh
$ arr_str=$@
$ declare -p arr_str
typeset arr_str='first entry second entry third entry'

# ...but quotes aren't needed to keep arguments together on array assignments.
$ arr=( $@ )
$ declare -p arr
typeset -a arr
arr=('first entry' 'second entry' 'third entry')

# in zsh, expanding an array always expands to all entries
$ printf '%s\n' $arr
first entry
second entry
third entry

# ...and unquoted string expansion doesn't do string-splitting by default:
$ printf '%s\n' $arr_str
first entry second entry third entry