goo*_*uy5 7 linux command-line error-handling output write
我正在尝试运行一个命令,将其写入文件,然后将该文件用于其他用途。
我需要的要点是:
myAPICommand.exe parameters > myFile.txt
Run Code Online (Sandbox Code Playgroud)
问题是myAPICommand.exe
失败了很多。我尝试修复一些问题并重新运行,但我遇到了“无法覆盖现有文件”的问题。我必须运行一个单独的rm
命令来清理空白myFile.txt
,然后重新运行myAPICommand.exe
.
这不是最严重的问题,但很烦人。
Ste*_*itt 11
运行后可以删除文件,如果命令失败,用
myAPICommand parameters > myFile.txt || rm myFile.txt
Run Code Online (Sandbox Code Playgroud)
但我建议改为破坏文件:
myAPICommand parameters >| myFile.txt
Run Code Online (Sandbox Code Playgroud)
请参阅shell 的控制和重定向运算符是什么?详情。
Evo*_*ter 11
您必须设置“noclobber”,请查看以下示例:
$ echo 1 > 1 # create file
$ cat 1
1
$ echo 2 > 1 # overwrite file
$ cat 1
2
$ set -o noclobber
$ echo 3 > 1 # file is now protected from accidental overwrite
bash: 1: cannot overwrite existing file
$ cat 1
2
$ echo 3 >| 1 # temporary allow overwrite
$ cat 1
3
$ echo 4 > 1
bash: 1: cannot overwrite existing file
$ cat 1
3
$ set +o noclobber
$ echo 4 > 1
$ cat 1
4
Run Code Online (Sandbox Code Playgroud)
“noclobber”仅用于覆盖,您仍然可以附加:
$ echo 4 > 1
bash: 1: cannot overwrite existing file
$ echo 4 >> 1
Run Code Online (Sandbox Code Playgroud)
要检查您是否设置了该标志,您可以输入echo $-
并查看您是否C
设置了标志(或set -o |grep clobber
)。
有什么要求吗?您可以简单地将输出存储在一个变量中,然后检查它是否为空。检查以下示例(请注意,您检查变量的方式需要根据您的需要进行微调,在示例中我没有引用它或使用任何类似${cmd_output+x}
检查变量是否已设置的内容,以避免编写仅包含空格的文件。
$ cmd_output=$(echo)
$ test $cmd_output && echo yes || echo no
no
$ cmd_output=$(echo -e '\n\n\n')
$ test $cmd_output && echo yes || echo no
no
$ cmd_output=$(echo -e ' ')
$ test $cmd_output && echo yes || echo no
no
$ cmd_output=$(echo -e 'something')
$ test $cmd_output && echo yes || echo no
yes
$ cmd_output=$(myAPICommand.exe parameters)
$ test $cmd_output && echo "$cmd_output" > myFile.txt
Run Code Online (Sandbox Code Playgroud)
不使用单个变量保存整个输出的示例:
log() { while read data; do echo "$data" >> myFile.txt; done; }
myAPICommand.exe parameters |log
Run Code Online (Sandbox Code Playgroud)