用于更改父 shell 目录的 Bash 脚本

标签 bash shell unix cd

<分区>

我想做什么

我创建了一个 shell 脚本,并将其添加到我的 $PATH 中,它将下载并为新的 Laravel 设置所有内容。项目。我希望通过将终端目录更改为新项目文件夹来结束脚本。

据我目前的了解,目前它只是更改脚本实际运行的子 shell 的目录。我似乎不知道该怎么做。任何帮助表示赞赏。谢谢!

#! /usr/bin/env bash

echo -e '\033[1;30m=========================================='

## check for a directory
if test -z "$1"; then
  echo -e ' \033[0;31m✖ Please provide a directory name'
  exit
fi

## check if directory already exist
if [ ! -d $1 ]; then
  mkdir $1
else
  echo -e ' \033[0;31m✖ The '"$1"' directory already exists'
  exit
fi

# move to directory
cd $1

## Download Laravel
echo -e ' \033[0;32m+ \033[0mDownloading Laravel...'
curl -s -L https://github.com/laravel/laravel/zipball/master > laravel.zip

## Unzip, move, and clean up Laravel
echo -e ' \033[0;32m+ \033[0mUnzipping and cleaning up files...'
unzip -q laravel.zip
rm laravel.zip
cd *-laravel-*
mv * ..
cd ..
rm -R *-laravel-*

## Make the /storage directory writable
echo -e ' \033[0;32m+ \033[0mMaking /storage directory writable...'
chmod -R o+w storage

## Download and install the Generators
echo -e ' \033[0;32m+ \033[0mInstalling Generators...'
curl -s -L https://raw.github.com/JeffreyWay/Laravel-Generator/master/generate.php > application/tasks/generate.php

## Update the application key
echo -e ' \033[0;32m+ \033[0mUpdating Application Key...'
MD5=`date +”%N” | md5`
sed -ie 's/YourSecretKeyGoesHere!/'"$MD5"'/' application/config/application.php
rm application/config/application.phpe

## Create .gitignore and initial git if -git is passed
if [ "$2" == "-git" ]; then
  echo -e ' \033[0;32m+ \033[0mInitiating git...'
  touch .gitignore
  curl -s -L https://raw.github.com/gist/4223565/be9f8e85f74a92c95e615ad1649c8d773e908036/.gitignore > .gitignore

  # Create a local git repo
  git init --quiet
  git add * .gitignore
  git commit -m 'Initial commit.' --quiet
fi

echo -e '\033[1;30m=========================================='
echo -e ' \033[0;32m✔ Laravel Setup Complete\033[0m'

## Change parent shell directory to new directory
## Currently it's only changing in the sub shell
filepath=`pwd`
cd "$filepath"

最佳答案

从技术上讲,您可以 source 脚本以在父 shell 中运行它,而不是生成子 shell 来运行它。这样,您对当前 shell 所做的任何更改(包括更改目录)都会保留。

source /path/to/my/script/script

. /path/to/my/script/script

但采购有其自身的风险,谨慎使用。

(外围相关:如何use scripts to change directories)

关于用于更改父 shell 目录的 Bash 脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13753157/

相关文章:

linux - 将 .dat 文件中的表格转换为 HTML 表格

macos - 为什么找不到让我匹配多个模式?

linux - 如何拆分unix文件中的数据

arrays - 无法在 bash 中打印数组值

python - 使用来自终端的参数调试 python 脚本

bash - avconv : flac to ogg conversion with metadata kept

linux - 编写运行其他用户拥有的另一个 shell 脚本的 shell 脚本

bash - 参数扩展的行为

命令行参数 C

linux - Unix/Linux : Sorting by numbers after a comma