如何在Shell脚本中操作数组 [英] how to manipulate array in shell script

查看:40
本文介绍了如何在Shell脚本中操作数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的脚本定义一个空数组.如果预定义条件为真,则应添加数组值.为此,我所做的是

I want my script to define an empty array. array values should be added if predefined condition gets true. for this what i have done is

declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        $FILES[$file_count] = $filename
        file_count=$file_count+1
fi

在执行此脚本时,我遇到了这样的错误

when executing this script i am getting some error like this

linux-softwares/launchers/join_files.sh: 51: [0]: not found

推荐答案

当数组中的设置数据无法使用$调用时:

When settings data in array does not recall with $:

declare -a FILES
file_count=0
if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        FILES[$file_count]=$filename
        file_count=$file_count+1
fi

不带$的文件.

这对我有用:

#!/bin/bash
declare -a FILES
file_count=0

file_ext='jpg'
SUPPORTED_FILE_TYPE='jpg'
filename='test.jpg'

if [ "$file_ext" != "$SUPPORTED_FILE_TYPE" ] ; then
        echo "$file_ext is not supported for this task."
else
        FILES[$file_count]=$filename
        file_count=$(($file_count+1))
fi

如您所见,对数学运算进行了一些修改$(()),但是文件分配是相同的...

As you see, a little modification $(( )) for math operation, but the FILES assignements is the same...

经过大量测试后指出,Ubuntu的默认shell似乎有点破折号,从而引发了错误.

As pointed out after lots of tests, Ubuntu default shell seems to be dash, which raised the error.

这篇关于如何在Shell脚本中操作数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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