2

I'm trying to copy some files from current directory in a bash script but the problem is that the cp command doesn't work with the current directory. I can use the following command without any problem on Backtrack 5 (based on Ubuntu) but not in Kali linux (based on Debian):

cp -f -v *.{html,txt,php} /var/www/

I can execute this command directly from the terminal by first changing directory to the directory where these files are. But using script I get the following error:

cp -f -v *.{html,txt,php} /var/www/
cp: cannot stat `*.{html,txt,php}': No such file or directory

Again I have no problem with this command in the script when I use Ubuntu.

  • 1
    Likely down to cp version. That syntax doesn't look like POSIX to me. – Sobrique Apr 16 '15 at 14:12
  • it's related to your shell and globbing. – PersianGulf Apr 16 '15 at 14:26
3

Your script interpreter is set to /bin/sh. On the system that expands the braced list, you are using the Bourne Again shell as /bin/sh. On the system that treats the braces as ordinary (non-meta) characters, and complains that the wildcard doesn't match anything, you are using the Debian Almquist shell as /bin/sh. Your interactive login shell is almost certainly explicitly /bin/bash on both systems.

If you are going to use such extensions to the POSIX shell language in a script, you must set the script interpreter to be the actual name of a shell that supports them. Conversely, if you are going to use /bin/sh as a script interpreter across diverse systems you should stick strictly to shell syntax that is POSIX-conformant.

Further reading

1

The error message cannot stat `*.{html,txt,php}' from cp indicates that either:

  • No matching file exists, or
  • You are using a shell that doesn't do brace expansion.

Which shell are you using on the system where the command fails? If it isn't bash but instead sh or dash, then that may explain what you are seeing. You could try giving your command *.html *.txt *.php instead of the brace pattern.

  • I use sh shell (.sh and bin/sh) . using separated extensions works but also I get some errors with -e parameter of echo (or maybe read, I don't remember). – bablod Apr 16 '15 at 15:00
  • Ok, I used #!/bin/bash instead of #!/bin/sh and now, it's working. but do I count on it? is it stable and won't make any future problems? – bablod Apr 16 '15 at 15:04
  • You can count on bash having this behavior; it is fully documented (search for "Brace Expansion" in the bash man page. As for echo -e, it's also documented when using the bash built-in; POSIX echo doesn't support -e and will print it verbatim. – dhag Apr 16 '15 at 15:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.