巴什 - 在一个变量保存$ @当被空间安全 [英] Bash - being space-safe when saving $@ in a variable

查看:83
本文介绍了巴什 - 在一个变量保存$ @当被空间安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

遍历这样的变量时,我有一个问题。我有prepared 2例子来说明这个问题。

I have a problem when looping over such a variable. I have prepared 2 examples to show the problem.

EX1:

#!/bin/bash
DIRS="$@"

for DIR in $DIRS; do
    echo "$DIR"
done

EX2:

#!/bin/bash
for DIR in "$@"; do
    echo "$DIR"
done

第二个例子按预期工作(和要求)。快速测试如下:

The second example works as expected (and required). A quick test follows:

$ ex1 "a b" "c"
a
b
c
$ ex2 "a b" "c"
a b
c

究其原因,我为什么要使用第一种方法是因为我希望能够到多个目录传递给程序或不使用当前目录。像这样:

The reason, why I want to use the first method is because I want to be able to pass multiple directories to the program or none to use the current dir. Like so:

[ $# -eq 0 ] && DIRS=`pwd` || DIRS="$@"

所以,我怎么例1是空间安全的吗?

So, how do I get example 1 to be space-safe?

推荐答案

使用数组,而不是一个简单的变量。

Use an array instead of a simple variable.

declare -a DIRS

DIRS=("$@")

for d in "${DIRS[@]}"
do echo "$d"
done

这产生的结果:

$ bash xx.sh a "b c" "d e f    g" h z
a
b c
d e f    g
h
z
$

这篇关于巴什 - 在一个变量保存$ @当被空间安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆