【发布时间】:2016-07-22 17:12:59
【问题描述】:
我正在开发一个项目,以在我的 GitLab CE 实例中远程创建一个存储库(该部分正在运行!),然后使用项目名称创建一个目录(正在运行!)并 cd 进入该目录(这里是我有问题的地方...),然后在本地初始化并添加远程存储库(工作!!!)
我遇到的问题只是更改为新目录。无论我使用下面显示的代码,还是简单地尝试cd "$1" 或cd "$*",我似乎都无法让它工作!
#!/bin/bash
dir="$*"
wd=$(pwd)
fulldir="$(pwd)/${dir// /\\ }/"
echo "Creating directory $dir"
mkdir -v "$dir"
cd "$dir"
echo "Changing current directory to $dir"
echo $dir
echo $fulldir
这段代码的输出是:
root@cana:~# ls
glnewproj test
root@cana:~# bash test Hello World
Creating directory Hello World
mkdir: created directory 'Hello World'
Changing current directory to Hello World
Hello World
/root/Hello\ World/
root@cana:~# ls
Hello World glnewproj test
root@cana:~# pwd
/root
如何cd 进入我新创建的目录?我完全被难住了。
编辑:
按 ghoti 键入函数并在 .bashrc 和我的测试脚本中对其进行测试。
直接从 bash 运行函数时:
root@cana:~# ls
glnewproj test test2
root@cana:~# mkcd "Hello World"
root@cana:~/Hello World#
在新的测试脚本中运行函数时:
root@cana:~# ls
glnewproj test test2
root@cana:~# cat test2
#!/bin/bash
mkcd() {
mkdir -p "$1" && cd "$1"
}
mkcd "$1"
root@cana:~# bash test2 "Hello World"
root@cana:~# ls
Hello World glnewproj test test2
所以脚本仍然作为子脚本运行,因此不会更新父 shell 的当前目录。在脚本末尾生成一个新的 shell 是我唯一的选择吗?
【问题讨论】:
-
您的
test2脚本仍然是一个单独的脚本,并且不在您的交互式shell 中运行。 test2 内部有自己的函数mkcd的事实并没有改变它在您通过在交互式shell 中运行bash创建的子shell 中运行的事实。不要运行 `bash test2 "Hello World",而是在运行的 shell 中将 test2 设为一个函数,然后运行该函数。 -
然而,我想要做的完全取决于它是一个脚本。
-
嗯,您现在有多个答案,包括您自己的答案,并且您明白为什么会遇到问题。如果您真的希望能够将交互式 shell 中的目录更改为由脚本创建的目录,那么有多种方法可以将它们组合在一起,我在回答中已经描述了一种。鉴于您问题的详细程度,我不可能知道它是否适用于您。
-
如果可以,我很懒惰,我在我的 bash 别名中有这个(→这里,
cd将在“脚本”结尾之后仍然有效):function mkcd(){/usr/bin/mkdir -p "$*"@ 987654335@}。因此,我可以在所有懒惰和没有 any 引号的情况下说:mkcd network testing