简体   繁体   中英

shell script : appending directory path and filename

I want to copy a file from a directory using shell script

Suppose I save the directory and file name seperately as

dir=/home/user/directory/
file=file_1

to copy the file Im using this command in my script

cp $dir$file .

But I get this error

/bin/cp omitting directory '/home/user/directory'

I have tried all combination eg. omitted the trail backslah from variable dir, etc but nothings working. I cant understand what is wrong with this code. Pleas help

Maybe the command $dir$file is not getting unpacked in the shell (ie only the directory variable is getting unpacked, not the file variable)!!!!!

It looks like you are having problem with expansion in cp $dir$file . In order to prevent possible problems, it is better to protect your variable with braces and double quote the full path/file to make sure you don't get caught by spaces in either the filename or heaven forbid the user's dirname:

cp "${dir}${file}" .

This will prevent the possibility the second $ is missed. Also make sure you have read access to other users /home (if you are root or using sudo you should be fine)

If you see this, when you somehow assign an empty string to file somewhere. Search your script for file= and unset file .

You can also debug this by adding

echo ".${file}."

in the line before the cp command. I'm pretty sure it prints .. , ie the variable is empty or doesn't exist.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM