0

I tried to move everything except a few items to a folder using a bash script with the following content. I tried these commands in the terminal first and got the expected results, but putting them inside a script produces the error mentioned below.

#! /bin/bash
shopt -s extglob
mv !(*.log | *.img) $1/build_files/ 2> /dev/null

ERROR:

build.sh: line 36: syntax error near unexpected token `(' 
build.sh: line 36: `    mv !(*.log|*.img) $1/build_files/ 2> /dev/null'

It'll be very helpful if someone could solve this. Thanks in advance.

3
  • 2
    you have a space in the shebang
    – user986805
    Feb 4, 2020 at 6:35
  • 1
    Such space in the shebang is allowed. I would prefer to remove it, but this is not the problem.
    – pa4080
    Feb 4, 2020 at 8:55
  • 1
    This is not the script that generates the error! The shown script has only 3 lines, but the error message is abut line 36. You must agree we are not seers, at least most of us are not :) Use the tool shellcheck to verify your script.
    – pa4080
    Feb 4, 2020 at 9:02

2 Answers 2

1

You can use find to do that:

find -maxdepth 1 -type f ! \( -name '*.img' -o -name '*.log' \) -exec mv {} $1/build_files/ \;

The argument -type f makes find look only for regular files. You have to remove it if you want to match any kind of file.

The argument -maxdepth 1 make find look for targets only on the current directory (by default the starting point of the search is the current directory).

See the find man page for more options and the different file types that you can target.

2
  • Thanks @TitouanT ! Your solution works for files but it does not move any folders in the directory! I would like to move all the folders as well.
    – Daniel
    Feb 5, 2020 at 4:08
  • 1
    remove the -type f then.
    – TitouanT
    Feb 5, 2020 at 10:02
0

A quick workaround to this, as I've implemented:

#!/bin/bash
mv * build_files/ 2> /dev/null
mv build_files/*.log ./ && mv build_files/*.imx ./ && mv build_files/*.sh ./

I know this involves multiple iterations, which are not necessary and I'm open for improvements.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .