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

柔情痞子 提交于 2020-01-03 06:50:37

问题


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?

#! /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

回答1:


You got that exactly backwards -- everything except the * 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.



来源:https://stackoverflow.com/questions/21924351/copying-files-with-wildcard-to-a-folder-in-a-bash-script-why-isnt-it-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!