![Bashスクリプトでスペースを含むパスにファイルをコピーする方法は? [コピー]](https://linux33.com/image/185706/Bash%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%97%E3%83%88%E3%81%A7%E3%82%B9%E3%83%9A%E3%83%BC%E3%82%B9%E3%82%92%E5%90%AB%E3%82%80%E3%83%91%E3%82%B9%E3%81%AB%E3%83%95%E3%82%A1%E3%82%A4%E3%83%AB%E3%82%92%E3%82%B3%E3%83%94%E3%83%BC%E3%81%99%E3%82%8B%E6%96%B9%E6%B3%95%E3%81%AF%EF%BC%9F%20%5B%E3%82%B3%E3%83%94%E3%83%BC%5D.png)
/tmp/template.txt
で指定されたディレクトリにファイルをコピーするサンプルスクリプト$1
。
script.sh コピー
if [ $# -eq 0 ]; then
echo No Argument
echo "Usage: $0 <path>"
else
cp /tmp/template.txt $1
fi
今後
wolf@linux:~$ ls -lh
total 4.0K
drwxrwxr-x 2 wolf wolf 4.0K Dis 31 10:08 'another directory'
wolf@linux:~$
テストスクリプト
wolf@linux:~$ copy_script.sh
No Argument
Usage: /home/wolf/bin/copy_script.sh <path>
wolf@linux:~$
現在のパスを使用したコードのテスト
wolf@linux:~$ copy_script.sh .
以降(有効)
wolf@linux:~$ ls -lh
total 8.0K
drwxrwxr-x 2 wolf wolf 4.0K Dis 31 10:08 'another directory'
-rw-rw-r-- 1 wolf wolf 12 Dis 31 10:26 template.txt
wolf@linux:~$
次に、テスト用のスペースがある別のディレクトリを使用します。
今回はディレクトリが引用されていても動作しなくなります(一重引用符/二重引用符は機能しません)。
wolf@linux:~$ copy_script.sh 'another directory'
cp: target 'directory' is not a directory
wolf@linux:~$
wolf@linux:~$ ls -lh another\ directory/
total 0
wolf@linux:~$
スペースを含むディレクトリ名を使用するにはどうすればよいですか?
答え1
上記の説明で述べたように、常にパラメータ拡張を引用してください。
cp /tmp/template.txt "$1"
ここで詳細を読むことができます。
https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html https://wiki.bash-hackers.org/syntax/pe
完全なコード
if [ $# -eq 0 ]; then
echo No Argument
echo "Usage: $0 <path>"
else
cp /tmp/template.txt "$1"
fi
これは空白の問題を解決します。
shellcheck
スクリプトを確認することもできます。これらの問題を特定することは非常に便利です。
$ shellcheck script.sh
In script.sh line 1:
if [ $# -eq 0 ]; then
^-- SC2148: Tips depend on target shell and yours is unknown. Add a shebang.
In script.sh line 5:
cp /tmp/template.txt $1
^-- SC2086: Double quote to prevent globbing and word splitting.
Did you mean:
cp /tmp/template.txt "$1"
For more information:
https://www.shellcheck.net/wiki/SC2148 -- Tips depend on target shell and y...
https://www.shellcheck.net/wiki/SC2086 -- Double quote to prevent globbing ...
$