简体   繁体   中英

Linux cp with variables

I'd like to copy a file that is specified by a variable in a Linux bash file.

This is how it does not work:

molecules = (1butene E2butene)
for molecule in ${molecules[*]}
do
    ### some stuff (works)
    formchk $molecule.chk $molecule.fchk
    ### cp doesn't work
    cp $molecule.com ${molecule}_scan.com
done

any ideas?

EDIT: it does also not work when I remove the spaces arround "=". cp throws no error, but I dont get a second file that is named molecule_scan.com

The main problem that I can see is the spaces around the = in your assignment:

molecules=(1butene E2butene)
for molecule in "${molecules[@]}"
do
  ### some stuff (works)
  formchk "$molecule.chk" "$molecule.fchk"
  ### cp doesn't work
  cp "$molecule.com" "${molecule}_scan.com"
done

Other things that I have changed are to use @ instead of * , to expand the array into a list of words for the loop. I've also added quotes around all of the variable expansions, which though unnecessary in this specific case, is a good habit to get into.

Remove the blanks in the assignment:

molecules=(1butene E2butene)

The shell delimits words at white spaces and assignments must read name=value .

Note that in your specific case you don't need non-standard shell arrays. Simply write

molecules="1butene E2butene"
for molecule in $molecules
do
  ### some stuff (works)
  formchk $molecule.chk $molecule.fchk
  ### cp doesn't work
  cp $molecule.com ${molecule}_scan.com
done

If you have trouble figuring out why something in the script does not work as expected, you can trace execution by adding a line with set -x before the rest of the script.

seems like it was a problem with the underscore this works:

cp $molecule.com ${molecule}\_scan.com

Thanks anyway for your help :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM