它是使用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 它的进程表项code>。 (有些炮弹会为一个子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).