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

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

问题描述

是否可以通过脚本更改当前目录?

Is it possible to change current directory from a script?

我想在Bash中创建一个用于目录导航的实用程序.我创建了一个如下所示的测试脚本:

I want to create a utility 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
}

原因是每个进程都有其自己的当前目录,并且当您从外壳执行程序时,它将在新进程中运行.标准的"cd","pushd"和"popd"内置在shell解释器中,因此它们会影响shell进程.

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函数,您将添加自己的进程内命令,然后任何目录更改都将反映在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.

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

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