I have a set of files like this in a directory named 'test':

cij_000.POSCAR cij_001.POSCAR cij_002.POSCAR ....... cij_029.POSCAR

It has also four other files in the same 'test' directory as:


What I want is, I want to create subdirectories within the 'test' directory according to the 'cij_xxx.POSCAR' file name (for example, as 'calc-xxx' are the subdirectory names), and then copy/link the other files (except the POSCAR file), and finally copy/link the 'cij_xxx.POSCAR' file to that subdirectory ('calc-xxx') as the name 'POSCAR'.

I tried the following bash script, somehow it is not doing anything (not creating the 'calc' directory and not linking the files thereby).

Could you please suggest me what should I correct, or any revised bash script suggestion?

Thanks in advance.

The bash script I tried (which didn't work unfortunately):


for s in $* ; do
    echo -n  $d ": "
mkdir calc-$d
        cd calc-$d
    ln -s ../INCAR ../KPOINTS ../POTCAR .
    ln -s ../$s POSCAR

1 Answer 1


A useful way to debug bash scripts is to echo each variable as it's set. At least on my system your for loop doesn't actually list all files, and the part where you extract the number xxx also does not work.. You could try

for filename in ./*.POSCAR ; do
    echo $filename
    d=$(echo "$filename" | grep -o -E '[0-9]+')
    echo -n $d ": \n"
    mkdir -p calc-$d
    cd calc-$d
    ln -sf ../INCAR ../KPOINTS ../POTCAR .
    ln -sf ../$filename POSCAR
    cd ..

The mkdir -p and ln -f flags removes errors from directories already existing, and makes ln overwrite any previous link.

  • $\begingroup$ Thanks. Could you tell me what is the role of this part '| grep -o -E '[0-9]+')'? $\endgroup$
    – Sak
    Commented Oct 25, 2022 at 5:24
  • 1
    $\begingroup$ It returns the part of $filename that contains one or more (ASCII) digits. The -E flag tells grep to interpret the pattern '[0-9]+' as a regular expression, and the -o flag means only the matching part is printed. $\endgroup$
    – Anyon
    Commented Oct 25, 2022 at 6:07
  • $\begingroup$ Thanks. It helps. $\endgroup$
    – Sak
    Commented Oct 26, 2022 at 7:26

You must log in to answer this question.

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