Aqui está o seu script com algumas modificações.
#!/bin/bash
# if file exist
#echo "Testing \ "$1""
if [ "$1" == "" ]
then
read -r -p "Enter the filename" file1
else
file1=$1
fi
if [ -f "$file1" ]
then
echo "$file1 does exist"
else
echo "$file1 does not exist!"
echo "Creating $file1"
echo "1" > "$file1"
exit 1
fi
#echo "Testing \ "$2""
if [ "$2" == "" ]
then
read -r -p "Enter the filename" file2
else
file1=$2
fi
if [ -f "$file2" ]
then
echo "$file2 does exist"
else
echo "$file2 does not exist!"
echo "Creating $file2"
echo "1" > "$file2"
exit 1
fi
if [ "$3" == "" ]
then
read -r -p "Enter the filename" file3
else
file3=$3
fi
# the following assumes that the data from the file is an integer
# and that it consists of only one line containing one value
# similar techniques can be used to do something much more powerful
data1=$(<"$file1")
data2=$(<"$file2")
# it's usually a good idea to validate data, but I have not included any validation
((data3 = data1 + data2))
echo "$data3" > "$file3" # overwrite the previous contents of the file with the new value
Contanto que nenhum arquivo1 ou arquivo2 mude, o conteúdo do arquivo3 será sempre o mesmo em repetidas execuções do script acima. Se file1 ou file2 não existir, um "1" será gravado como um valor padrão.
Aqui está uma versão melhorada do script usando funções:
#!/bin/bash
checkarg () {
local filename=$1
if [ "$filename" == "" ]
then
read -r -p "Enter the filename" filename
fi
echo "$filename"
}
checkfile () {
local filename=$1
if [ -f "$filename" ]; then
echo "$filename does exist"
else
echo "$filename does not exist!"
echo "Creating $filename"
echo "1" > "$filename"
# you could remove this exit if you want the script to continue
# with newly created files instead of exiting
exit 1
fi
}
file1=$(checkarg "$1")
checkfile "$file1"
file2=$(checkarg "$2")
checkfile "$file2"
file3=$(checkarg "$3")
data1=$(< "$file1")
data2=$(< "$file2")
((data3 = data1 + data2))
echo "$data3" > "$file3"