【问题标题】:ksh --> is it possible to run a command on the parent shell (main shell) from within a subshell?ksh --> 是否可以在子 shell 中在父 shell(主 shell)上运行命令?
【发布时间】:2014-05-26 05:28:56
【问题描述】:
#!/usr/bin/ksh


if [ $# -ne 1 ]; then
        echo "[*]\t Please see usage..."
        echo "[*]\t Usage: $0 <store_number>"
        exit 1
fi


if [ -z "$1" ]; then
        echo "[*]\t Please see usage..."
        echo "[*]\t Usage: $0 <store_number>"
  exit 1
fi


Store_Number=$1
EPS_Directory="/apps/epsadmin_90000"$Store_Number"/EPS"


cd $EPS_Directory

我正在尝试编写一个简单的脚本来更改我的主 shell 中的目录。 我可以在子 shell 中更改目录(如上所示),但很明显,当脚本运行完成后,它会将我踢回外壳,我又回到了原来的目录中。

是否可以从子外壳中将命令传递给外壳?我可以将 cd 命令传递给外壳吗?

例如,如果我运行:

./cd.sh 2001

我希望我的目录是:

/apps/epsadmin_900002001/EPS

一旦我回到外壳。

【问题讨论】:

标签: shell scripting ksh cd subshell


【解决方案1】:

不,这是不可能的。

相反,您可以创建一个函数:

mycd() {
  if [ $# -ne 1 ]; then
    echo "[*]\t Please see usage..."
    echo "[*]\t Usage: $0 <store_number>"
    return 1
  fi

  if [ -z "$1" ]; then
    echo "[*]\t Please see usage..."
    echo "[*]\t Usage: $0 <store_number>"
    return 1
  fi

  Store_Number=$1
  EPS_Directory="/apps/epsadmin_90000$Store_Number/EPS"

  cd "$EPS_Directory"
}

...并将其存储在自己的文件中并获取它:

. $HOME/.fun/mycd.sh

Shell 函数在主进程中运行,与在子进程中运行的脚本不同。

【讨论】:

    【解决方案2】:

    感谢您的所有帮助!这是我的解决方案。

    #   create dj file in /users/(YOUR_NUID) directory
    #   paste the dj function into this file.   (vi dj)  (hit i to enter edit mode) (right click to paste)  (hit esc)  (type :wq)
    #   source the dj file containing dj() functon by adding this to .profile:
    #   . $HOME/dj
    #   reload .profile by typing . ./.profile
    
    #   then to run the function simply type dj <storenumber> to jump between EPS directory folders.
    
    
    dj(){
    
    Store_Number=$1
    EPS_Directory="/apps/epsadmin_90000"$Store_Number"/EPS"
    
        if [ -e $(echo $EPS_Directory) ]; then
            cd $EPS_Directory
            echo "You are now in directory: $EPS_Directory"
        else
            echo "Directory $EPS_Directory does not exist."
        fi 
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-24
      • 2014-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-16
      • 1970-01-01
      相关资源
      最近更新 更多