BスクリプトのLinux "cp"コマンド

BスクリプトのLinux

このbashスクリプトがあります。

#!/bin/bash

OriginFilePath="/home/lv2eof/.config/google-chrome/Profile 1/"
OriginFileName="Bookmarks"
OriginFilePathAndName="$OriginFilePath""$OriginFileName"

DestinationFilePath="/home/Config/Browser/Bookmarks/ScriptSaved/Chrome/Profile 1/"
DestinationFileName=$(date +%Y%m%d-%H%M%S-Bookmarks)
DestinationFilePathAndName="$DestinationFilePath""$DestinationFileName"

echo cp \"$OriginFilePathAndName\" \"$DestinationFilePathAndName\"
cp \"$OriginFilePathAndName\" \"$DestinationFilePathAndName\"

コマンドラインから実行すると、次の結果が表示されます。

[~/]
lv2eof@PERU $$$ csbp1
cp "/home/lv2eof/.config/google-chrome/Profile 1/Bookmarks" "/home/Config/Browser/Bookmarks/ScriptSaved/Chrome/Profile 1/20211207-001444-Bookmarks"
cp: target '1/20211207-001444-Bookmarks"' is not a directory

[~/]
lv2eof@PERU $$$ 

したがって、エラーが発生し、ファイルはコピーされません。それにもかかわらず、コマンドラインからコマンドを実行すると、次のようになります。

[~/]
lv2eof@PERU $$$ cp "/home/lv2eof/.config/google-chrome/Profile 1/Bookmarks" "/home/Config/Browser/Bookmarks/ScriptSaved/Chrome/Profile 1/20211207-001444-Bookmarks"

[~/]
lv2eof@PERU $$$ 

ご覧のとおり、すべてがうまく機能し、ファイルがコピーされました。このコマンドはbashスクリプトの内部と外部で同じように動作する必要はありませんか?私は何が間違っていましたか?

ベストアンサー1

気づくのは難しいかもしれませんが、メッセージには2つのヒントがあります。

cp: target '1/20211207-001444-Bookmarks"' is not a directory
           |                           |
           |                           +-- Notice quote
           +-- Space in target

つまり、1/20211207-001444-Bookmarks"ディレクトリではありません。では、なぜそんなことを言うのでしょうか?

スクリプトには次のものがあります。

cp \"$OriginFilePathAndName\" \"$DestinationFilePathAndName\"

渡す脱出引用符、引用符がパラメータの一部であることを意味します。回避策:脅威引用符をリテラルテキストとして表示します。彼らシリーズへ変数の値として。

しなければならない:

cp "$OriginFilePathAndName" "$DestinationFilePathAndName"

簡単に言えば、bashに知らせるために変数を引用します。これはパラメータとして説明する必要があります。

あなたの質問によると、実際のパラメータはcp2ではなく4になります。

  1. "/home/lv2eof/.config/google-chrome/Profile
  2. 1/Bookmarks"
  3. "/home/Config/Browser/Bookmarks/ScriptSaved/Chrome/Profile
  4. 1/20211207-001444-Bookmarks"

つまり、1、2、3を4にコピーします。

おすすめ記事