它是使用CD和CD的好办法 - 在其他目录中的shell脚本的一些计算指令 [英] Is it a good way to use cd and cd - commands in a shell script for some computation in another directory

查看:106
本文介绍了它是使用CD和CD的好办法 - 在其他目录中的shell脚本的一些计算指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的CD在我的shell脚本进入到一个目录对一些计算和再次使用CD - 回来。它是用一个好办法吗?我的脚本是:

I use cd in my shell script to enter into a directory for some computation and again use cd - to come back. Is it a good way to use? My script is:

input_dir=/home/abc/2001/01/
cd $input_dir
#Execute some programm with ifile.txt e.g.
awk '$1 > 99 {printf "%.2f" "$1"}' ifile.txt > ofile.tx 
cd -

或者我们应该总是提到的路径名?这样的:

or we should always mention the path name? like:

input_dir=/home/abc/2001/01/
awk '$1 > 99 {printf "%.2f" "$1"}' $input_dir/ifile.txt > $input_dir/ofile.txt

您可以请建议是否有什么简单的方法来减少文字?

Can you please suggest if there is anything easy way to reduce the texts?

推荐答案

把它放在一个子shell:

Put it in a subshell:

(cd "$input_dir" && exec awk '$1 > 99 {printf "%.2f" "$1"}' ifile.txt > ofile.tx)

因此​​,当子shell退出时,你会自动回到你原来的目录,因为 CD 仅适用于子shell(只包含 AWK 命令)。

Thus, when the subshell exits, you're automatically back to your original directory, because the cd only applied to that subshell (containing only the awk command).

EXEC 确保你不会产生额外的开销,因为它会导致子shell来替换与 AWK 。 (有些炮弹会为一个子shell里面的最后一个命令自动完成)。

The exec ensures that you're not incurring extra overhead, as it causes the subshell to replace its process table entry with the awk. (Some shells will do this automatically for the last command inside a subshell).

这篇关于它是使用CD和CD的好办法 - 在其他目录中的shell脚本的一些计算指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆