0

OS: Ubuntu

I have the folder testfolder/subfolder with content backup file1.txt file2.txt testFolder

And I have script testfolder/testMv.sh

Now I'm inside of the bash session and do the following:

echo "$SHELL"
cd testfolder/subfolder
echo "bla" > file1.txt
echo "bla" > file2.txt
mkdir trs
ls
mv "!(backup)" backup

output

/bin/bash
backup  file1.txt  file2.txt  trs

Work perfectly, all files and folder except backup moved, no error. Live is great.

Now put all the same to the testfolder/testMv.sh

echo "bla" > file1.txt
echo "bla" > file2.txt
mkdir trs
ls
echo mv "!(backup)" backup
mv "!(backup)" backup

In the same bash, on the same machine doing:

cd testfolder/subfolder
../testMv.sh

Output:

backup  file1.txt  file2.txt  trs
mv !(backup) backup
mv: cannot stat '!(backup)': No such file or directory

Why???

PS I know how to avoid usage of mv, I just want to understand why the sh script works in different way from the shell itself.

New contributor
FreemanRU is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
6
  • 3
    You may need to enable the shell's extglob option - see Parenthesis works in bash shell itself, but not in bash script. You script also lacks a shebang. Jun 23 at 22:17
  • 3
    What do you expect "!(backup)" to do? In bash's interactive mode it'll be treated as a history reference (unless extglob is enabled). Scripts normally run in non-interactive mode, so history is disabled. Note that it won't work as an extended glob expression (either interactively or in a script), because it's in double-quotes. Jun 23 at 22:22
  • 3
    Are you sure you used double quotes around !(backup) when you successfully used mv interactively? The quotes would have disabled the globbing, even if extglob was enabled.
    – Kusalananda
    Jun 23 at 22:24
  • @GordonDavisson "!()" means "exclude", !() mean history. @
    – FreemanRU
    Jun 24 at 9:10
  • @steeldriver this is the bingo, thanks. Strange that I'vnt found this post during hours of searching.
    – FreemanRU
    Jun 24 at 9:16

0

Your Answer

FreemanRU is a new contributor. Be nice, and check out our Code of Conduct.

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

Browse other questions tagged or ask your own question.