我在变量中有字符串,我想把它从变量写入文件,但只有当这个字符串和文件的内容不同时。
You can use the following script:
string="foo"
# Use diff to check if the file's content and the variable differ
# <(...) is called "process substitution"
diff file <(cat <<< "$string")
# diff returns 0 if both inputs are the same
[ $? -ne 0 ] || cat <<< "$string" > file
You will have to store the content of the file in a variable and do a check if the variables are same. Something like:
[[ "$var" != "$checkvar" ]] && echo "$var" >> file || echo "content same"
$ var=jaypalsingh # Create a variable
$ cat file # Content of the file
jaypalsingh
$ checkvar=$(<file) # Add the content of the file to variable
$ [[ "$var" != "$checkvar" ]] && echo "$var" >> file || echo "content same"
content same
$ var=jaypal
$ [[ "$var" != "$checkvar" ]] && echo "$var" >> file || echo "content same"
$ cat file
jaypalsingh
jaypal
Now this will get messier and complicated if you file is big with many lines. The variables will need to have explicit new lines in them.
$ var=jaypalsingh$'\n'jaypal # Variable with new line
$ echo "$var"
jaypalsingh
jaypal
$ cat file
jaypalsingh
jaypal
$ checkvar=$(<file)
$ [[ "$var" != "$checkvar" ]] && echo "$var" >> file || echo "content same"
content same
Quotes around [[..]]
are not needed but usage here will protect against meta-characters as suggested in the comments by that other guy . He also makes another valid point regarding usage of echo
here. printf
will be more suited here to generate your variable.
>> echo hello world > file
>> cat file
hello world
>> str="hello world"
>> if [ "$(diff file <(echo $str))" != "" ]; then echo $str >> file; fi
>> cat file
hello world
>> str="hello SO"
>> if [ "$(diff file <(echo $str))" != "" ]; then echo $str >> file; fi
>> cat file
hello world
hello SO
If you want to overwrite file
instead of appending to it, use echo $str > file
.
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.