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

查看:54
本文介绍了从 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
}

原因是每个进程都有自己的当前目录,当你从 shell 执行一个程序时,它会在一个新进程中运行.标准的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天全站免登陆