从脚本改变当前目录 [英] Change current directory from a script

查看:86
本文介绍了从脚本改变当前目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能从脚本改变当前目录?

Is it possible to change current directory from a script?

我想创建一个在bash目录导航UTIL。我创建了一个测试脚本如下所示:

I want to create a util for directory navigation in bash. I have created a test script that looks like the following:

#!/bin/bash
cd /home/artemb

当我执行从的bash脚本shell当前目录不会改变。是否有可能在所有从脚本改变当前shell目录?

When I execute the script from the bash shell the current directory doesn't change. Is it possible at all to change the current shell directory from a script?

推荐答案

您需要将您的脚本转换为一个shell函数:

You need to convert your script to a shell function:

#!/bin/bash
#
# this script should not be run directly,
# instead you need to source it from your .bashrc,
# by adding this line:
#   . ~/bin/myprog.sh
#

function myprog() {
  A=$1
  B=$2
  echo "aaa ${A} bbb ${B} ccc"
  cd /proc
}

原因是,每个进程都有自己的当前目录中,当你从shell执行一个程序是在一个新的进程中运行。标准的CD,PUSHD和POPD,使他们影响shell进程被内置到外壳间preTER。

The reason is that each process has its own current directory, and when you execute a program from the shell it is run in a new process. The standard "cd", "pushd" and "popd" are builtin to the shell interpreter so that they affect the shell process.

通过使您的程序外壳的功能,要添加自己的过程中的命令,然后任意目录的变化得到反映在shell进程。

By making your program a shell function, you are adding your own in-process command and then any directory change gets reflected in the shell process.

这篇关于从脚本改变当前目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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