如何成功重定向程序的输出?

时间:2015-07-15 07:49:36

标签: bash shell unix

当我的一个程序返回非零退出代码时,我想避免重定向其输出。这是可能的,如果是这样,我该怎么做?

我失败的尝试:

echo foo > file
false | cat > file

这导致file为空。我想要的行为是只在程序成功时调整file

我也想知道,如果输出非空,是否可以只更新文件,而不使用多个文件。

2 个答案:

答案 0 :(得分:1)

你可以像这样使用它:

> 07-15 13:09:52.067  17443-17443/antivirus.dc.lab.texttospeech E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: antivirus.dc.lab.texttospeech, PID: 17443
    java.lang.RuntimeException: Unable to start activity ComponentInfo{antivirus.dc.lab.texttospeech/antivirus.dc.lab.texttospeech.MainActivity}: java.lang.NullPointerException: Attempt to get length of null array
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
     Caused by: java.lang.NullPointerException: Attempt to get length of null array
            at antivirus.dc.lab.texttospeech.MainActivity.onCreate(MainActivity.java:40)
            at android.app.Activity.performCreate(Activity.java:5990)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
            at android.app.ActivityThread.access$800(ActivityThread.java:151)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5254)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

out=$(some_command) && echo "$out" > outfile 仅在echo "$out" > outfile成功时才会执行。

答案 1 :(得分:0)

如果避免空文件的创建和删除不是必需的,也许是一个很好的替代方法

false > file || rm -f file