简体   繁体   中英

Shell script cp not working (but working in terminal) Mac os X

I've been recently learning about shell scripting, and am stumped by a weird error:

My simple script (test.command):

#!/bin/sh
clear
cd /Users/Stan/Desktop/testFolder
ls 
cp "earth.png lol.png"
read -p "Done, press ENTER to finish"

Whenever I run the script (double clicking the .command file), here is the output (copied from terminal window):

earth.png
usage: cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file target_file
       cp [-R [-H | -L | -P]] [-fi | -n] [-apvX] source_file ... target_directory
Copy was done...?
earth.png
Done, press ENTER to finish

The cp ALWAYS gives a 'usage' error, and WONT copy anything, but now if i manually run the SAME exact commands, in order in terminal (copy of terminal window):

Stans-Mac-mini:testFolder Stan$ ls
earth.png
Stans-Mac-mini:testFolder Stan$ cp earth.png lol.png
Stans-Mac-mini:testFolder Stan$ ls
earth.png   lol.png
Stans-Mac-mini:testFolder Stan$ 

The file got copied without any error! Please help me fix this, I couldn't find any solutions online, help is greatly appreciated!

Change cp command

cp "earth.png" "lol.png"

cp command format is : cp <from> <to> . Your command has it like cp "<single-file>" . Both earth.png and lol.png are within the quotes and that makes it a single file. Second argument is missing and thats the reason for "usage error"

When you quote both the source and the destination arguments provided to cp as one string, it only gets the one argument.
The command:

cp "earth.png lol.png"

attempts to copy one file with the name "earth.png lol.png" (which by the way is a perfectly valid file name), but then fails to provide a second argument.
Instead, quote each individual argument:

cp "earth.png" "lol.png"

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