我尝试将一个变量的内容写入文件,但如果文件不存在则创建它:
到目前为止,我得到了以下代码:
echo "$Logstring" >> $fileLog
当文件不存在时,我缺少什么?为什么会报错?是否需要if条件语句?
使用touch
命令:
touch $fileLog
echo "$Logstring" >> $fileLog
echo "string" >> file
本身就可以正常工作。我们需要一种方法来创建文件和一个或多个父目录,而这里touch
失败了。至少我的touche
来自GNU coreutils 8.28。 - taniusmkdir -p $(basename $fileLog)
。首先执行此操作以确保文件夹存在,然后像上面那样触摸文件,最后继续流式传输到该文件。 - user2085368 #! /bin/bash
VAR="something to put in a file"
OUT=$1
if [ ! -f "$OUT" ]; then
mkdir -p "`dirname \"$OUT\"`" 2>/dev/null
fi
echo $VAR >> $OUT
# the important step here is to make sure that the folder for the file exists
# and create it if it does not. It will remain silent if the folder exists.
$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out hello/how/are/you/file.out
geee: ~/src/bash/moo
$ sh out another/file/lol.hmz
geee: ~/src/bash/moo
$ find .
.
./out
./another
./another/file
./another/file/lol.hmz
./hello
./hello/how
./hello/how/are
./hello/how/are/you
./hello/how/are/you/file.out
geee: ~/src/bash/moo
$ cat ./hello/how/are/you/file.out
something to put in a file
something to put in a file
geee: ~/src/bash/moo
$ cat ./another/file/lol.hmz
something to put in a file
>>
重定向操作符会在文件不存在时创建它。 - chrisaycock$fileLog
包含一个空格 - 用双引号将其包裹起来,以防止它破坏乐趣。 - Ben Graham