0

Sample script to copy /tmp/template.txt file to any directory as specified in $1.

copy_script.sh

if [ $# -eq 0 ]; then
    echo No Argument
    echo "Usage: $0 <path>"
else
    cp /tmp/template.txt $1
fi

Before

wolf@linux:~$ ls -lh
total 4.0K
drwxrwxr-x 2 wolf wolf 4.0K Dis  31 10:08 'another directory'
wolf@linux:~$ 

Testing script

wolf@linux:~$ copy_script.sh 
No Argument
Usage: /home/wolf/bin/copy_script.sh <path>
wolf@linux:~$ 

Testing code with current path

wolf@linux:~$ copy_script.sh .

After (it works)

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:~$ 

Then, I test with another directory which has space in it.

This time, it doesn't work anymore even though the directory has been put it quote (both single/double quote doesn't work).

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:~$ 

How do I make this work with directory name with space in it?

Wolf
  • 1,631

1 Answers1

0

As mentioned in the comment above, always quote your parameter expansion.

cp /tmp/template.txt "$1"

You can read more about it here.

https://www.gnu.org/software/bash/manual/html_node/Shell-Parameter-Expansion.html https://wiki.bash-hackers.org/syntax/pe

Full code

if [ $# -eq 0 ]; then
    echo No Argument
    echo "Usage: $0 <path>"
else
    cp /tmp/template.txt "$1"
fi

This should fix your issue with whitespace.

You also might want to check shellcheck script. It's very useful to identify issue like this.

$ 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 ... $