首页 > 解决方案 > [@] 在 bash 中是什么意思?

问题描述

我有以下遗留脚本,它将整个文件移动到构建目录中。它正在移动所有.js文件,但没有移动任何.py结束文件。如果一个目录包含一个.js结束文件,它只会移动那个文件,如果这个目录不包含任何.js文件,它就不会移动任何东西。我想我需要修改${files[@]}部分以包含.py文件。有人能告诉我是什么"${files[@]}"意思吗?或者更好地如何包含移动.py结束文件。

#!/bin/bash -e
dirs=("app")
files=("server.js")

function compile-dir {
    babel $1 --out-dir "./build/$1"
}

function compile-file {
    babel $1 --out-dir "./build"
}

rm -rf ./build

for dir in "${dirs[@]}"
do
    compile-dir "$dir"
done

for file in "${files[@]}"
do
    compile-file $file
done

mkdir "./build/resources"
cp -R "./resources/" "./build/"
cp -R "./config" "./build/"

标签: bashdirectory

解决方案


直接解决您的问题:"What does [@] mean in bash?"[@]数组变量结合使用以扩展该数组中的所有元素。以下是一些 bash/python 等价物

重击

# Declare array
array=("e1" "e2" "e3")

# Print array one line
echo ${array[@]}

# Iterate over array elements
for element in "${array[@]}"
do
    echo $element
done

Python

# Declare array
array=["e1", "e2", "e3"]

# Print array one line
print(array)

# Iterate over array elements
for element in array:
    print(element)

不过,更一般地说,您似乎无法理解您继承的这个遗留 bash 脚本。这里标有一些注释。

#!/bin/bash -e
# This script uses the babel compiler to compile a list of directories
# and files. To use this script properly make sure to populate
# the 'dirs' and 'files' arrays below before running

# Manage directories/files in two arrays
dirs=("app")
files=("server.js")

# compile-dir
# Use babel to compile a direcotry and output it into the build dir
# @param <dirname>
function compile-dir {
    babel $1 --out-dir "./build/$1"
}

# compile-file
# Use babel to compile a file and output it into the build dir
# @param <filename>
function compile-file {
    babel $1 --out-dir "./build"
}

#################################
#         -- MAIN --            #
#################################

# Begin by deleting the existing build dir
rm -rf ./build

# Compile all dirs in dirs array
for dir in "${dirs[@]}"
do
    compile-dir "$dir"
done

# Compile all files in files array
for file in "${files[@]}"
do
    compile-file $file
done

# Move 'resources' and 'config' dirs into 'resources' subdir of './build'
mkdir "./build/resources"
cp -R "./resources/" "./build/"
cp -R "./config" "./build/"

推荐阅读