选择多个文件时$ @的行为如何?

问题描述 投票:1回答:2

所以,假设我有6个文件都是相同的类型。在我的具体情况下,所有这些都是zip文件,我想选择所有这些文件并“通过它们”一个“解压缩”所有这些文件的shell脚本。

我已经可以逐个选择,因为脚本只是这样做:

#!/bin/bash
DIR=$(dirname "$@")
exec unzip "$@" -d "${DIR}"

因此它将“zip文件”解压缩到我所拥有的位置。 现在,当我选择多个文件(也就是多个文件)时。我不知道会发生什么,因为我不完全理解“解析”到脚本中的内容。 我找到了这个What does $@ mean in a shell script?

所以我想知道如何做对。非常感谢。

bash shell unix file-io
2个回答
4
投票

Fixing Your Script: Iterating Over Arguments

如果您正在调用命令(如unzip),一次只接受一个参数(您希望传递的类型),那么您需要迭代它们。那是:

#!/bin/bash
for arg in "$@"; do       # or just "for arg do"
  dir=$(dirname "$arg")
  unzip "$arg" -d "$dir"
done

Literal Answer (What The Original Syntax Did)

"$@"扩展到位置参数的完整列表。这在实践中意味着什么?

假设您的代码被调用:

./yourscript "Directory One/file1.zip" "Directory Two/file2.zip"

在这种情况下,您将拥有:

# this is what your code would try to do (it's an error!)
DIR=$(dirname "Directory One/file1.zip" "Directory Two/file2.zip")

...其次是:

# also doesn't work, since "unzip" only takes a single zipfile argument
# ...and because the above dirname fails, DIR is empty here
unzip "Directory One/file1.zip" "Directory Two/file2.zip" -d "$DIR"

0
投票

引自the official manual

@ - 从一个开始扩展到位置参数。当扩展发生在双引号内时,每个参数都会扩展为单独的单词。也就是说,"$@"相当于"$1" "$2" ...。如果双引号扩展发生在一个单词中,则第一个参数的扩展与原始单词的开头部分连接,最后一个参数的扩展与原始单词的最后一部分连接。当没有位置参数时,"$@"$@扩展为空(即,它们被移除)。

© www.soinside.com 2019 - 2024. All rights reserved.