boltup_im_coding
boltup_im_coding

Reputation: 6665

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

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

Upvotes: 30

Views: 31273

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295650

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.

Upvotes: 44

Related Questions