shell脚本将文件从一个目录复制到另一个目录

时间:2022-04-20 01:47:06

Trying to write a simple script to copy some files in OS X 10.9. Here's the content..

尝试编写一个简单的脚本来复制OS X 10.9中的一些文件。这是内容..

SRC_DIR="~/Library/Preferences-Old"

DST_DIR="~/Library/Preferences"

FILEN="test.txt"

cp $SRC_DIR/$FILEN $DST_DIR

Gives me the output:

给我输出:

cp: ~/Library/Preferences-Old/test.txt: No such file or directory

Of course, the above is wrong. The exact same cp command in terminal directly does the trick. What am I doing wrong here?

当然,以上是错误的。终端中完全相同的cp命令直接起作用。我在这做错了什么?

3 个解决方案

#1


~ is one of the few exceptions to the rule "When in doubt, quote". As others have pointed out, a quoted ~ is not subject to expansion. However, you can still quote the rest of the string:

〜是“当有疑问时引用”规则的少数例外之一。正如其他人所指出的那样,引用〜不受扩展影响。但是,您仍然可以引用字符串的其余部分:

SRC_DIR=~"/Library/Preferences-Old"
DST_DIR=~"/Library/Preferences"

Note that depending on the values assigned to the two *_DIR variables, it's not enough to quote the values being assigned; you still need to quote their expansions.

请注意,根据分配给两个* _DIR变量的值,仅引用分配的值是不够的;你还需要引用他们的扩展。

FILEN="test.txt"

cp "$SRC_DIR/$FILEN" "$DST_DIR"

#2


Your double-quotes are preventing the shell from converting your ~ into an actual path. Observe:

您的双引号会阻止shell将您的〜转换为实际路径。注意:

$ echo ~
/home/politank_z

$ echo "~"
~

~ isn't an actual location, it is shorthand for the path of your home directory.

〜不是实际位置,它是主目录路径的简写。

#3


As already mentioned double-quotes disabled ~ expansion.

如前所述,双引号禁用〜扩展。

Better approach is to use HOME variable:

更好的方法是使用HOME变量:

SRC_DIR="$HOME/Library/Preferences-Old"
DST_DIR="$HOME/Library/Preferences"

#1


~ is one of the few exceptions to the rule "When in doubt, quote". As others have pointed out, a quoted ~ is not subject to expansion. However, you can still quote the rest of the string:

〜是“当有疑问时引用”规则的少数例外之一。正如其他人所指出的那样,引用〜不受扩展影响。但是,您仍然可以引用字符串的其余部分:

SRC_DIR=~"/Library/Preferences-Old"
DST_DIR=~"/Library/Preferences"

Note that depending on the values assigned to the two *_DIR variables, it's not enough to quote the values being assigned; you still need to quote their expansions.

请注意,根据分配给两个* _DIR变量的值,仅引用分配的值是不够的;你还需要引用他们的扩展。

FILEN="test.txt"

cp "$SRC_DIR/$FILEN" "$DST_DIR"

#2


Your double-quotes are preventing the shell from converting your ~ into an actual path. Observe:

您的双引号会阻止shell将您的〜转换为实际路径。注意:

$ echo ~
/home/politank_z

$ echo "~"
~

~ isn't an actual location, it is shorthand for the path of your home directory.

〜不是实际位置,它是主目录路径的简写。

#3


As already mentioned double-quotes disabled ~ expansion.

如前所述,双引号禁用〜扩展。

Better approach is to use HOME variable:

更好的方法是使用HOME变量:

SRC_DIR="$HOME/Library/Preferences-Old"
DST_DIR="$HOME/Library/Preferences"