我正在使用以下命令
envconsul env | awk '{print "export " $0}' > ~/.profile
如果envconsul失败(即,命令在管道之前的第一部分)-那么.profile文件将为空。我不要我只想使命令失败,而不在管道(|)部分之后执行。
这是在POSIX shell一线式中实现还是我需要编写bash脚本?
到目前为止,我尝试添加set -o pipefail,添加&&,但是它们都不起作用。有任何建议吗?
答案 0 :(得分:2)
您需要一个临时文件和pipefail:
set -o pipefail
if envconsul env | awk '{print "export " $0}' > ~/.profile.tmp
then
mv ~/.profile.tmp ~/.profile
echo "Success"all stages but the last are ignored, making it harder to check whether the commands succeeded.
fi
没有临时文件,~/.profile
在管道完成之前被截断,因此成功与失败无关紧要。
在没有pipefail
的情况下,envconsul env
的退出状态将被忽略,因为通常只考虑最后一个阶段。
如果希望它与POSIX兼容,则可以先将envconsul env
的结果写入文件,然后独立检查其状态。
答案 1 :(得分:2)
正如我在注释中建议的那样,写入临时文件,如果命令失败,则退出。如果成功,请将临时文件移到适当位置。
这是我的看法:
ICopy = np.uint8(I) # I is input image
edge = cv2.Canny(ICopy,180,200) # Edge detection
f = cv2.dft(np.float32(edge), flags=cv2.DFT_COMPLEX_OUTPUT) #Perform DFT
f_shift = np.fft.fftshift(f) # Shift 0,0 to centre
f_complex = f_shift[:,:,0] + 1j*f_shift[:,:,1]
f_abs = np.abs(f_complex) + 1 # calculate magnitude and value lies between 1 and 1e6
f_bounded = 20 * np.log(f_abs) # To scale down values
f_img = 255 * f_bounded / np.max(f_bounded) # Scale between 0 and 255
f_img1 = f_img.astype(np.uint8) # Format arary to print
figure(figsize=(10,10))
plt.subplot(121);plt.imshow(edge , cmap = 'gray')
plt.subplot(122);plt.imshow(f_img1 , cmap = 'gray')
答案 2 :(得分:0)
两线:
output="$(envconsul env 2>/dev/null | awk '{print "export " $0}' )"
test -n "${output}" && echo "${output}" > ~/.profile
编辑(评论后):
当您确实需要直接检查envconsul
的结果(而不是长度)时,可以执行类似的操作
output="$(envconsul env 2>/dev/null)
if [ $? -eq 0 ]; then
echo "${output}" | awk '{print "export " $0}' ) > ~/.profile
else
echo "Some other action"
fi
答案 3 :(得分:0)
在此应用程序中使用管道可能很吸引人,但它会使错误处理变得复杂。
当数据量不大时,将命令的输出存储在字符串中并进行标准错误检查会更容易:
environment=$(./envconsul env) && awk '{print "export " $0}' <<<"${environment}" >~/.profile