将带有通配符 (*) 的文件复制到 bash 脚本中的文件夹 - 为什么它不起作用?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21924351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 09:39:13  来源:igfitidea点击:

Copying files with wildcard (*) to a folder in a bash script - why isn't it working?

linuxbashscripting

提问by boltup_im_coding

I am writing a bash script that creates a folder, and copies files to that folder. It works from the command line, but not from my script. What is wrong here?

我正在编写一个 bash 脚本来创建一个文件夹,并将文件复制到该文件夹​​中。它可以从命令行运行,但不能从我的脚本运行。这里有什么问题?

#! /bin/sh
DIR_NAME=files

ROOT=..
FOOD_DIR=food
FRUITS_DIR=fruits

rm -rf $DIR_NAME
mkdir $DIR_NAME
chmod 755 $DIR_NAME

cp $ROOT/$FOOD_DIR/"*" $DIR_NAME/

I get:

我得到:

cp: cannot stat `../food/fruits/*': No such file or directory

回答by Charles Duffy

You got that exactly backwards -- everything exceptthe *character should be double-quoted:

你完全倒退了——除了*字符之外的所有东西都应该用双引号引起来:

#!/bin/sh
dir_name=files

root=..
food_dir=food
fruits_dir=fruits

rm -rf "$dir_name"
mkdir "$dir_name"
chmod 755 "$dir_name"

cp "$root/$food_dir/"* "$dir_name/"

Also, as a matter of best-practice / convention, non-environment variable names should be lower case to avoid name conflicts with environment variables and builtins.

此外,作为最佳实践/约定的问题,非环境变量名称应小写,以避免与环境变量和内置变量的名称冲突。