Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 
like image 918
boltup_im_coding Avatar asked Feb 21 '14 02:02

boltup_im_coding


People also ask

How do wildcards work in bash?

When we need to search for anything using shell commands then we need to define a pattern for searching. Wildcard characters are used to define the pattern for searching or matching text on string data in the bash shell. Another common use of wildcard characters is to create regular expressions.

How do I copy a file from one directory to another in bash?

Copy a File ( cp ) You can also copy a specific file to a new directory using the command cp followed by the name of the file you want to copy and the name of the directory to where you want to copy the file (e.g. cp filename directory-name ). For example, you can copy grades. txt from the home directory to documents .

How do you copy a wildcard character in command?

You can use the wildcard characters asterisk ( * ) and question mark ( ? ) as part of the file name argument. For example, part* loads the files part-0000 , part-0001 , and so on. If you specify only a folder name, COPY attempts to load all files in the folder.

Can you SCP with wildcard?

2) Unfortunatly, scp will not support wild cards as like rcp. However, you can copy a directory with it's files and sub directories as, scp ezhilara@ssng0011dwk:/tmp/ .


1 Answers

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.

like image 164
Charles Duffy Avatar answered Sep 17 '22 15:09

Charles Duffy