Bash脚本打开,读取,然后写入然后保存

我是这个bash脚本的新东西。 你能告诉我一些编写Bash脚本的例子。 我想写一个脚本,可以从一个文件名读取并保存到一个variables; 递增variables的值并将该variables写回文件并保存。 这是我迄今为止开始的并且坚持到底的事情。

#!/bin/bash # if file exist #echo "Testing \ "$1"" if [ -f "$1" ]; then echo "$1 does exist" else echo "$1 does not exist!" echo "Creating $1" touch $1 echo "This is test" > $1 exit 1 fi #echo "Testing \ "$2"" if [ "$2" == "" ]; then echo "Enter the filename" elif [ -f "$2" ]; then echo "$2 Fille does exist" else echo "$2 File doesn't exist" echo "Creating $2" touch $2 exit 1 fi counter=1 echo -n "Enter a file name : " read file if [ ! -f $file ] then echo "$file not a file!" exit 1 fi 

这是你的脚本进行一些修改。

 #!/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 

只要file1或file2都没有改变,file3的内容在上面脚本的重复运行中总是一样的。 如果file1或file2不存在,则将“1”写入默认值。

以下是使用函数的脚本的改进版本:

 #!/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"