0

我写了这个显然没有问题的脚本:

#!/bin/bash

DATA=/home/badouble/STORE/rawData_v1r0
LOGS=/home/badouble/bABaReC/CDAS_Selection_log

for dir in $DATA/*/
do
     dir=${dir%*/}
     echo $dir
     ARR=$(echo $dir | tr "/" " ")
     echo ${ARR[1]}   

 done

但它不会产生所需的输出,如下所示:

/home/badouble/STORE/rawData_v1r0/2011-12

/home/badouble/STORE/rawData_v1r0/2012-01

/home/badouble/STORE/rawData_v1r0/2012-02

/home/badouble/STORE/rawData_v1r0/2012-03

/home/badouble/STORE/rawData_v1r0/2012-04

/home/badouble/STORE/rawData_v1r0/2012-05

/home/badouble/STORE/rawData_v1r0/2012-06

/home/badouble/STORE/rawData_v1r0/2012-07

/home/badouble/STORE/rawData_v1r0/2012-08

/home/badouble/STORE/rawData_v1r0/2012-09

/home/badouble/STORE/rawData_v1r0/2012-10

/home/badouble/STORE/rawData_v1r0/2012-11

/home/badouble/STORE/rawData_v1r0/2012-12

/home/badouble/STORE/rawData_v1r0/2013-01

/home/badouble/STORE/rawData_v1r0/2013-02

/home/badouble/STORE/rawData_v1r0/2013-03

它应该打印数组 $ARR 的第二个元素,而不是空白行。

为什么不呢?

4

3 回答 3

1

你不需要也不需echo要这样做tr

要创建数组,只需使用IFSread,如下所示,因为这些是 shell 内置命令,所以效率更高:

IFS=/ read -a ARR <<< "$dir"
echo "${ARR[1]}"
于 2013-03-08T11:16:19.073 回答
0

您需要将echo 的输出捕获( )

ARR=( $(echo $dir | tr "/" " ") )

或者

 ARR=( `echo $dir | tr "/" " "` )

或完全省去tr

ARR=( `echo ${dir//\// }` )

${var//from/to}通过在扩展中使用替换:\/转义为“来自”。或者更好(更健壮),完全省去子流程:

ARR=( ${dir//\/ /} )
于 2013-03-08T11:05:59.840 回答
0

一个额外的括号:

ARR=($(echo $dir | tr "/" " "))

x=$(command) 这会将命令的结果分配给变量 x

x=($(command))这将首先执行命令并将结果存储在数组 x 中

于 2013-03-08T11:08:48.317 回答