Home > Software engineering >  Bash echo some lines to terminal and some lines to file
Bash echo some lines to terminal and some lines to file

Time:03-30

I have this code bash code called xyz_to_mol:

CARBONS=$(grep -ow "C" $1 | wc -l)
HYDROGENS=$(grep -ow "H" $1 | wc -l)
OXYGENS=$(grep -ow "O" $1 | wc -l)

ATYPES=0
ARRAY=($CARBONS $HYDROGENS $OXYGENS)

for i in "${ARRAY[@]}"
do
        if [ $i -gt 0 ]; then
                ((ATYPES =1))
        fi
done

echo "Choose co0, co1 or co2 basis set"
read BASIS_SET

echo "BASIS"
echo "$BASIS_SET"
echo ""
echo ""
echo "Atomtypes="$ATYPES" Generators=0 Integrals=1.00D-15 Angstrom"
echo "Charge=6.0 Atoms="$CARBONS""
grep "C" $1
echo "Charge=1.0 Atoms="$HYDROGENS""
grep "H" $1
if [ $OXYGENS -gt 0 ]; then
    echo "Charge=8.0 Atoms="$OXYGENS""
    grep "O" $1
fi

This works just as I want except for one thing: The line "Choose co0, co1 or co2 basis set" should not be written to output file but instead as an instruction to the command line for the user. So If I use the script like this:

xyz_to_mol ketone.xyz > ketone.mol

the user should see an instruction: "Choose co0, co1 or co2 basis set". Then he or she should write co0, co1 or co2 and the output file ketone.mol should not contain the line "Choose co0, co1 or co2 basis set". How can I implement this?

CodePudding user response:

Prompts are typically written to standard error, not standard output. You can do that explicitly:

echo "Choose co0, co1 or co2 basis set" >&2
read BASIS_SET

or implicitly with the -p option to read:

read -p "Choose co0, co1, or co2 basis set" BASIS_SET

CodePudding user response:

One alternative is to send the file name as a parameter and write to the output file inside your script instead:

echo "BASIS" > $2
echo "$BASIS_SET" >> $2
echo "" >> $2
echo "" >> $2
echo "Atomtypes="$ATYPES" Generators=0 Integrals=1.00D-15 Angstrom" >> $2
echo "Charge=6.0 Atoms="$CARBONS"" >> $2
grep "C" $1 >> $2
echo "Charge=1.0 Atoms="$HYDROGENS"" >> $2
grep "H" $1 >> $2
if [ $OXYGENS -gt 0 ]; then
    echo "Charge=8.0 Atoms="$OXYGENS"" >> $2
    grep "O" $1 >> $2
fi

And call the script like:

xyz_to_mol ketone.xyz ketone.mol
  • Related