linux - 新手 : Script to change directories

标签 linux scripting ksh

以下是我正在尝试的更大脚本的片段。我只想让这部分识别参数是一个目录,然后 cd 到该目录:即 ./larj/etc。

#!/bin/ksh
# Filename: larj.sh

if [ $# -gt 1 ]; then
    echo "0 or 1 arguments allowed."
    exit
fi
if [ -f "$1" ]; then
    echo "directory only."
    exit
else
    if [ -d "$1" ]; then
        cd $1
    fi
fi

当我以/etc 作为参数运行脚本时,似乎没有任何反应;它保持在同一个目录中没有错误。 有人对如何让它更改目录有任何建议吗?

谢谢

最佳答案

cd 发生在脚本的 shell 中。

当脚本结束时,它的 shell 退出,您返回到运行脚本之前的目录。为了更改目录,您可以

mkdir testdir
. ./your_script.sh testdir

在脚本的末尾,您将被移动到目录 testdir。

关于linux - 新手 : Script to change directories,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44725383/

相关文章:

bash - Bash脚本: 'Syntax error: “fi” unexpected' within nested statement

bash - shell脚本中的这一行是做什么的?

使用启用 https url 的用户名和密码进行身份验证的 Curl API 和命令行选项

arrays - 调整文件重命名脚本,以便它搜索子目录中的每个文件

shell - 在嵌套的for循环中的shell脚本中运行shell脚本

linux - 如何在 ksh 中编写脚本以删除记录列表中的最后一条记录?

linux - 在 KSH 中生成 12 位十六进制数

linux - 在 Korn Shell 的 for 循环中为变量赋值

linux - Bash 相对日期(x 天前)

Python脚本手动执行但不通过cron